# Create a WordPress shortcode to show recent posts

URL: https://wp24x7.com/how-to-create-and-add-a-short-code-to-display-recent-posts/
Updated: 2026-11-29
Type: blog post
Audience: WordPress developers and site owners

> 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.

## Key facts

- 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.**

> **Quick answer**
Put the function below in a small plugin, call `add_shortcode( 'recent_posts', ... )`, and type `[recent_posts count="3"]` in any post or widget. If you only need a plain list, the Latest Posts block needs no code at all.

## 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
<?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?

| 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:

```php
$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:

```php
$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:

```php
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](/wordpress-speed-optimization) 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:

```php
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.

- **Plugin development** Bespoke blocks, shortcodes and plugins. [WordPress plugin development](/wordpress-plugin-development)
- **Custom development** Features built to your brief. [WordPress development](/wordpress-development)
- **Slow site?** Find the real cause before adding caching layers. [Speed optimization](/wordpress-speed-optimization)

**Want this built and tested for you?**
A developer reads your brief, today.
[Post a project](/post-project)
[Call the help desk](/help-desk)

## Frequently asked questions

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.
