in 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');

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email