Advertisement
brasofilo

Shortcode to print posts inside a page

Oct 29th, 2011
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. <?php
  2. /*
  3.  * Shortcode to print posts inside a page
  4.  * Example: [query category_name="wordpress-code" count=3]
  5.  * Code grabbed from: http://goo.gl/my24k
  6.  */
  7.  
  8. function queryposts($atts){
  9.     extract( shortcode_atts( array(
  10.     'category_id' => '',
  11.     'category_name' => '',
  12.     'tag' => '',
  13.     'day' => '',
  14.     'month' => '',
  15.     'year' => '',
  16.     'count' => '5',
  17.     'author_id' => '',
  18.     'author_name' => '',
  19.     'order_by' => 'date',
  20.     ), $atts));
  21.  
  22.     $output = '';
  23.  
  24.     $query = array();
  25.  
  26.     // create the query string
  27.     if ($category_id != '') $query[] = 'cat=' .$category_id;
  28.     if ($category_name != '') $query[] = 'category_name=' .$category_name;
  29.     if ($tag != '') $query[] = 'tag=' . $tag;
  30.     if ($day != '') $query[] = 'day=' . $day;
  31.     if ($month != '') $query[] = 'monthnum=' . $month;
  32.     if ($year != '') $query[] = 'year=' . $year;
  33.     if ($count) $query[] = 'posts_per_page=' .$count;
  34.     if ($author_id != '') $query[] = 'author=' . $author_id;
  35.     if ($author_name != '') $query[] = 'author_name=' . $author_name;
  36.     if ($order_by) $query[] = 'orderby=' . $order_by;
  37.  
  38.     ob_start(); // output to buffer
  39.  
  40.     // backup the $post variable so it doesn't mess it up if called again
  41.     $backup = $post;
  42.  
  43.     $posts = new WP_Query(implode('&',$query));
  44.  
  45.     while ($posts->have_posts()): $posts->the_post();
  46.  
  47.     // copy here the post layout from your theme's index.php file -- this is just a example ?>
  48.     <h2> <?php the_title(); ?></h2>
  49.     <?php the_content(); ?>
  50.  
  51.     <?php
  52.     endwhile;
  53.  
  54.     $post = $backup; // restore the original $post
  55.     wp_reset_query();
  56.  
  57.     // store the buffer output in the $output variable
  58.     $output = ob_get_contents();
  59.     ob_end_clean();
  60.  
  61.     return $output;
  62. }
  63.  
  64. add_shortcode('query', 'queryposts');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement