Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

Recent posts shortcode

Type [recent_posts] to show a list of your latest posts anywhere. Choose how many and from which category: [recent_posts count="3" category="news"].

  • Type PHP
  • Runs Where you put the [recent_posts] shortcode
  • Category Shortcodes
  • Tested with WordPress 7.1
PHP
<?php

// [recent_posts count="5" category="news"]
$atts  = shortcode_atts( array( 'count' => 5, 'category' => '' ), $atts, 'recent_posts' );
$posts = get_posts(
	array(
		'numberposts'      => max( 1, min( 20, (int) $atts['count'] ) ),
		'category_name'    => sanitize_title( $atts['category'] ),
		'post__not_in'     => array( (int) get_the_ID() ),
		'suppress_filters' => false,
	)
);
if ( ! $posts ) {
	return '';
}
$out = '<ul class="recent-posts">';
foreach ( $posts as $post ) {
	$out .= '<li><a href="' . esc_url( get_permalink( $post ) ) . '">' . esc_html( get_the_title( $post ) ) . '</a> <time datetime="' . esc_attr( get_the_date( 'c', $post ) ) . '">' . esc_html( get_the_date( '', $post ) ) . '</time></li>';
}
return $out . '</ul>';

How to use it

Type [recent_posts] in a post, a page or a Shortcode block.

In these packs

  • Shortcodes: Handy shortcodes for dates, breadcrumbs, buttons, share links, members-only content and more.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.