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.
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
On this page
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().
| Need | Best choice |
|---|---|
| A plain list in the block editor | Latest Posts block |
| Custom markup or classes | Shortcode |
| Same list in a classic widget or template | Shortcode with do_shortcode() |
| Visual editing in the Site Editor | A 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"]What does each part do?
| Part | Why 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, max | Keep the count sensible, so count="99999" cannot be requested. |
sanitize_title() | Turns the category attribute into a clean slug. |
ignore_sticky_posts | Stops sticky posts jumping to the top. |
no_found_rows | Skips 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 echo | A 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?
| Symptom | Cause | Fix |
|---|---|---|
| Shortcode shows as plain text | Plugin inactive, tag name differs, or the place does not process shortcodes | Activate it, match the tag, use a post or widget |
| Output at the top of the page | The function used echo | Return a string |
| List does not update | A page cache holds the old list | Purge the cache when posts publish |
| Not found in the block editor | Wrong block | Use 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
- Return, do not echo
Output is a string.
- Escape everything
Every printed value is escaped for its context.
- Cap the count
And sanitize every attribute.
- Prefix names
Function names cannot collide.
- Test three places
A post, a widget and the Shortcode block.
- Test edge cases
An empty result returns an empty string, and a category that does not exist is handled.
- 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.
Bespoke blocks, shortcodes and plugins.
WordPress plugin development02Custom developmentFeatures built to your brief.
WordPress development03Slow site?Find the real cause before adding caching layers.
Speed optimizationA developer reads your brief, today.
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 answerWhere 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 answerWhy 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 answerWhy 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 answerWhy 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 answerWhy 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 answerWhat 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 answerCan 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 answerShould 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 answerWhy 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 answerHow 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 answerCan 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 answerKeep reading
Want an engineer on it?
Tell us what is wrong in plain words. A person reads it, today.