How To Create WordPress Recent Posts Shortcode

recent posts display shortcode

These days almost every other wordpress theme comes with prebuilt shortcodes and that applies to both premium and free themes. However if you are a developer who wants to learn how to build a shortcode for displaying recent posts, you will find this guide helpful. If you have used wordpress.com you must have experience of using those large number of shortcodes that are available there.

One of the most popular and frequently used shortcode is recent posts display, but how do you create it in your own theme for a self hosted wordpress website? You can use the code snippet provided below to create a shortcode that will allow you to add a list of most recent posts with dates they were published on.

The shortcode can display 10 most recently published posts anywhere on you want to display them. For instance you can show them in a post, page or in a sidebar widgets as well. There are different attributes that are passed into the WP_Query object. Therefore if you want to customize to display specific posts, you can do that by changing the attributes on the shortcode.

The shortcode is a perfect option to be used in page builders to build unique layouts and it is a great option for custom layout where you want to display recent posts in a unique way.

Add the code below in your functions.php file:

function chiefthemes_posts_shortcode($atts, $content = NULL)
{
    $atts = shortcode_atts(
        [
            'orderby' => 'date',
            'posts_per_page' => '10'
        ], $atts, 'recent-posts' );
    
    $query = new WP_Query( $atts );

    $output = '<ul class="recent-posts">';

    while($query->have_posts()) : $query->the_post();

        $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a> - <small>' . get_the_date() . '</small></li>';

    endwhile;

    wp_reset_query();

    return $output . '</ul>';
}
add_shortcode('recent-posts', 'chiefthemes_posts_shortcode');

Leave a Reply

Your email address will not be published. Required fields are marked *