Custom Query Shortcode: Run a Loop inside Any Post/Page


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function custom_query_shortcode($atts) {
  2.  
  3. // EXAMPLE USAGE:
  4. // [loop the_query="showposts=100&post_type=page&post_parent=453"]
  5.  
  6. // Defaults
  7. extract(shortcode_atts(array(
  8. "the_query" => ''
  9. ), $atts));
  10.  
  11. // de-funkify query
  12. $the_query = preg_replace('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $the_query);
  13. $the_query = preg_replace('~&#0*([0-9]+);~e', 'chr(\\1)', $the_query);
  14.  
  15. // query is made
  16. query_posts($the_query);
  17.  
  18. // Reset and setup variables
  19. $output = '';
  20. $temp_title = '';
  21. $temp_link = '';
  22.  
  23. // the loop
  24. if (have_posts()) : while (have_posts()) : the_post();
  25.  
  26. $temp_title = get_the_title($post->ID);
  27. $temp_link = get_permalink($post->ID);
  28.  
  29. // output all findings - CUSTOMIZE TO YOUR LIKING
  30. $output .= "<li><a href='$temp_link'>$temp_title</a></li>";
  31.  
  32. endwhile; else:
  33.  
  34. $output .= "nothing found.";
  35.  
  36. endif;
  37.  
  38. wp_reset_query();
  39. return $output;
  40.  
  41. }
  42. add_shortcode("loop", "custom_query_shortcode");
  43.  
  44.  
  45.  
  46.  
  47. [loop the_query="showposts=20&post_type=page&post_parent=453&ord=ASC"]

URL: http://digwp.com/2010/01/custom-query-shortcode/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+DiggingIntoWordpress+%28Digging+Into+WordPress%29

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.