WordPress Advanced shortcode for recent posts


Example

This functions takes parameter for how many recent posts you want to display.

Ex : you want to display only five recent posts. Just passed the arguments with posts="5" (you can pass any number of recent posts that you want to display).

Function fetch only five recent posts from database.

// recent-posts is going to be our shortcode.
add_shortcode('recent-posts', 'recent_posts_function');

// Functions takes parameter such as posts="5".
function recent_posts_function($atts){
   extract(shortcode_atts(array(
      'posts' => 1,
   ), $atts));

   $return_string = '<ul>';
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
   if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
      endwhile;
   endif;
   $return_string .= '</ul>';

   wp_reset_query();
   return $return_string;
}

Eg. echo do_shortcode( '[recent-posts posts="5"]' );