Advertisement
ridgey28

WP Shortcode Display posts and Excerpts in the Text Widget

Feb 16th, 2013
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.06 KB | None | 0 0
  1. /*WordPress Shortcode to display the latest 5 posts
  2.  * PLEASE NOTE: This may not work on certain themes or for everyone!
  3.  * Add the following code to your functions.php then add the shortcode [recent-posts] to the text widget
  4.  * box in the WP Dashboard widgets section.  You may need to make changes to your stylesheet's .textwidget or .widget_text classes respectively.
  5.  * Want to display more posts?  Change posts_per_page to the number you wish
  6.  * Want to display Pages? Change post_type to 'pages'
  7.  */
  8. function my_recent_posts($atts){
  9.  $query = new WP_Query( array( 'post_type' =>'post','orderby' => 'date', 'posts_per_page' => '5'));
  10.         $list = '<ul class="recent-posts">';
  11.  
  12.             while($query->have_posts()) : $query->the_post();
  13.  
  14.                 $list .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a>' . '<br />' . get_the_excerpt() . '</li>';
  15.  
  16.             endwhile;
  17.  
  18.             wp_reset_postdata();
  19.  
  20.         return $list . '</ul>';
  21. }
  22. add_filter('widget_text', 'do_shortcode');/*Needed to display shortcode in widget*/
  23. add_shortcode('recent-posts', 'my_recent_posts');
  24. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement