WordPress

WordPress Recent Posts Shortcode

On WordPress.com you automatically get are a large number of shortcodes that you can use on your blog. Here you can view all the default shortcodes on WordPress.com.

One of these shortcodes is to display the most recent posts by using the shortcode display posts.

The below is a code snippet you can use to add a list of the most recent posts and the date they were published. This shortcode displays the last 10 posts in a list anywhere you use the shortcode. The attributes on the shortcode will be passed into the WP_Query object therefore if you want to change what posts are displayed by simply changing the attributes on the shortcode.

/**
 * Shortcode to display the most recent posts
 * The attributes passed into the function will be passed into the WP_Query object to modify the query
 * By default the last 10 posts will be displayed
 * 
 * @param $atts
 * @param $content
 * 
 * @return string
 */
function pu_recent_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', 'pu_recent_posts_shortcode');
Back to top

Members Download

Comments

  1. Aaron says:

    what are you using to make code snippets look like sublime text?

    1. Paul says:

      Hi Aaron

      I use a third party JS library called Prism. I have a tutorial on how you can implement this with WordPress hope it helps https://paulund.co.uk/display-code-snippet-in-wordpress

Leave a Reply

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