Paulund

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

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring