Skip to content
Development

Create a WordPress shortcode to show recent posts

Build a safe shortcode that lists recent posts with WP_Query, with attributes, escaping and the block alternative that needs no code.

By WP24×7 engineers5 min readPublished November 30, 2019Updated November 29, 2026

At a glance

A how-to for building a WordPress shortcode that lists recent posts with WP_Query. It gives complete code with attributes, a capped count, escaping and a reset of post data, then covers dates, true or false attributes, safe caching and common failures. It also explains when the Latest Posts block is the better choice.

Updated November 29, 2026 · For WordPress developers and site owners

  • For WordPress developers and site owners
  • Code lives in a small plugin or a child theme
  • Rule one return the output, never echo it
  • Safety cap the count, sanitize attributes, escape output
  • No-code option the Latest Posts block
  • Test in a post, a widget and the Shortcode block

A shortcode is a bracketed tag, like [recent_posts count="3"], that WordPress replaces with dynamic content. Register it with `add_shortcode()`, build the output as a string, escape everything, and return it.

Do I need code at all?

If you only want a list of the latest posts, use the Latest Posts block, which has options for count, categories, excerpts and layout. A shortcode earns its place when you need markup the block cannot give you, or the same list must appear in a classic widget, a page builder text area, or a template through do_shortcode().

NeedBest choice
A plain list in the block editorLatest Posts block
Custom markup or classesShortcode
Same list in a classic widget or templateShortcode with do_shortcode()
Visual editing in the Site EditorA custom block

What is the code?

Put it in a small plugin (a single PHP file in wp-content/plugins/) or a child theme. Take a backup first.

<?php
/**
 * Plugin Name: Recent Posts Shortcode
 */

function mysite_recent_posts_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'count'    => 5,
			'category' => '',
		),
		$atts,
		'recent_posts'
	);

	$query = new WP_Query(
		array(
			'post_type'           => 'post',
			'posts_per_page'      => min( 20, max( 1, absint( $atts['count'] ) ) ),
			'category_name'       => sanitize_title( $atts['category'] ),
			'ignore_sticky_posts' => true,
			'no_found_rows'       => true,
		)
	);

	if ( ! $query->have_posts() ) {
		return '';
	}

	$out = '<ul class="recent-posts">';
	while ( $query->have_posts() ) {
		$query->the_post();
		$out .= sprintf(
			'<li><a href="%s">%s</a></li>',
			esc_url( get_permalink() ),
			esc_html( get_the_title() )
		);
	}
	wp_reset_postdata();

	return $out . '</ul>';
}
add_shortcode( 'recent_posts', 'mysite_recent_posts_shortcode' );

Use it in any post, page or text widget:

[recent_posts count="3" category="news"]
A shortcode turns a short tag into a list built by PHP

What does each part do?

PartWhy it is there
shortcode_atts()Merges typed attributes with your defaults and ignores unknown ones. The third argument lets other code filter the attributes.
absint, min, maxKeep the count sensible, so count="99999" cannot be requested.
sanitize_title()Turns the category attribute into a clean slug.
ignore_sticky_postsStops sticky posts jumping to the top.
no_found_rowsSkips an unneeded count query, a small gain for a simple list.
esc_url(), esc_html()Escape output. Escape late as a habit, even for titles an editor wrote.
wp_reset_postdata()Restores the global post so the rest of the page is not affected.
return, not echoA shortcode that echoes prints at the wrong place.

The function name has a prefix (mysite_) so it cannot collide with another plugin's.

How do I add a date or excerpt?

Inside the loop, add more markup and escape each part:

$out .= sprintf(
	'<li><a href="%1$s">%2$s</a> <time datetime="%3$s">%4$s</time></li>',
	esc_url( get_permalink() ),
	esc_html( get_the_title() ),
	esc_attr( get_the_date( 'c' ) ),
	esc_html( get_the_date() )
);

For an excerpt, use esc_html( get_the_excerpt() ). Keep the HTML simple, and style with CSS classes rather than inline styles.

How do I add a true or false attribute?

Attributes arrive as strings, so show_date="false" is the text "false", which PHP treats as true. Convert it properly:

$atts = shortcode_atts(
	array( 'count' => 5, 'show_date' => 'yes' ),
	$atts,
	'recent_posts'
);
$show_date = filter_var( $atts['show_date'], FILTER_VALIDATE_BOOLEAN );

FILTER_VALIDATE_BOOLEAN understands "yes", "true", "1" and "on" as true and "no", "false", "0" and "off" as false. Then use $show_date to decide whether to add the date markup from the section above.

How do I use it in a theme template?

Shortcodes in PHP templates are run with do_shortcode(), and the result is already built HTML from your function, which is escaped inside it:

echo do_shortcode( '[recent_posts count="3"]' );

If you are in a template anyway, you could call a plain function instead. Shortcodes are mainly for content editors.

What goes wrong most often?

SymptomCauseFix
Shortcode shows as plain textPlugin inactive, tag name differs, or the place does not process shortcodesActivate it, match the tag, use a post or widget
Output at the top of the pageThe function used echoReturn a string
List does not updateA page cache holds the old listPurge the cache when posts publish
Not found in the block editorWrong blockUse the Shortcode block, or paste it in a paragraph

Should I cache the query?

For a small site, no. For a busy site with the shortcode on many pages, wrap the result in a transient keyed by the attributes, and clear it when a post is published. Measure first: simple queries like this are fast on a healthy database. If your site is slow, a speed review finds the real causes before you add caching layers.

How do I cache the list safely?

A transient with a version number lets you clear every cached list when any post changes:

add_action( 'save_post_post', function () {
	update_option( 'mysite_rp_version', time(), false );
} );

// Inside the shortcode function, before running the query:
$key    = 'mysite_rp_' . get_option( 'mysite_rp_version', 0 ) . '_' . md5( wp_json_encode( $atts ) );
$cached = get_transient( $key );
if ( false !== $cached ) {
	return $cached;
}
// ...build $out as before, then:
set_transient( $key, $out . '</ul>', HOUR_IN_SECONDS );

Changing the version number makes old keys unreachable, and they expire on their own. If you use an object cache, transients are stored there, which is faster still.

Checklist before you ship it

  1. Return, do not echo

    Output is a string.

  2. Escape everything

    Every printed value is escaped for its context.

  3. Cap the count

    And sanitize every attribute.

  4. Prefix names

    Function names cannot collide.

  5. Test three places

    A post, a widget and the Shortcode block.

  6. Test edge cases

    An empty result returns an empty string, and a category that does not exist is handled.

  7. Keep it in a plugin

    Not in a theme you may change.

When a block is better

If the list should be edited visually, or you want it in the Site Editor, a custom block is a better fit than a shortcode. A shortcode remains handy for content written in classic editors, widgets and templates, and for people who will type it by hand.

Want this built and tested for you?

A developer reads your brief, today.

FAQ

Questions people ask

12 answers. Can't find yours? Ask an engineer.

Do I need a shortcode, or can I use a block?

For a plain list of recent posts, the Latest Posts block does the job without code. Use a shortcode when you need custom markup, or content that must work in widgets or classic editors.

Link to this answer
Where should the shortcode code go?

In a small plugin, so it keeps working if you change themes. A child theme's functions.php works for theme-specific output.

Link to this answer
Why must a shortcode return instead of echo?

WordPress places the returned string where the shortcode sits. Echoing prints it at the top of the page, before the content.

Link to this answer
Why does show_date=false still show the date?

Shortcode attributes are strings, and the text false counts as true in PHP. Convert it with filter_var and FILTER_VALIDATE_BOOLEAN.

Link to this answer
Why does my shortcode show as plain text?

The plugin is inactive, the tag name differs from the one registered, or the text sits somewhere that does not process shortcodes, such as some custom fields.

Link to this answer
Why cap the count attribute?

Without a cap, anyone who can edit a post could type a huge count and make the page run a very heavy query. The example limits it between 1 and 20 using absint, min and max.

Link to this answer
What does wp_reset_postdata do?

It restores the global post after a custom loop, so the rest of the page, such as the template and other widgets, keeps working with the correct current post.

Link to this answer
Can I use the shortcode in a theme template?

Yes, with echo do_shortcode and the tag. If you are already in a template, a plain PHP function is simpler. Shortcodes are mainly for content editors.

Link to this answer
Should I cache the recent posts query?

Only on a busy site where the shortcode appears on many pages. A transient keyed by the attributes, cleared when a post is saved, works. Measure first, because this query is fast on a healthy database.

Link to this answer
Why does the list not update after I publish a post?

A page cache stores the list until it is purged. Set a sensible cache lifetime or clear the cache when posts are published, and check any transient you added.

Link to this answer
How do I add an excerpt or date to each item?

Add more markup inside the loop and escape each part, for example esc_html of get_the_excerpt, and a time element using get_the_date. Keep the HTML simple and style with classes.

Link to this answer
Can WP24x7 build a custom block or plugin for this?

Yes. Custom blocks, shortcodes and small plugins are development work. Post a project describing the output you want and a developer will scope it.

Link to this answer

Keep reading

Want an engineer on it?

Tell us what is wrong in plain words. A person reads it, today.