# Recent Posts Shortcode

> Adds a [recent_posts] shortcode that lists your latest posts anywhere, optionally from one category and with dates.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: shortcode, recent-posts, posts
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/recent-posts-shortcode/

## Code

```php
add_shortcode( 'recent_posts', function ( $atts ) {
    $atts = shortcode_atts( array(
        'number'    => 5,
        'category'  => '',
        'show_date' => 'no',
    ), $atts, 'recent_posts' );

    $args = array(
        'numberposts'         => min( 50, max( 1, absint( $atts['number'] ) ) ),
        'post_status'         => 'publish',
        'ignore_sticky_posts' => true,
        'no_found_rows'       => true,
        'post__not_in'        => array( get_the_ID() ),
    );

    if ( '' !== $atts['category'] ) {
        $args['category_name'] = sanitize_title( $atts['category'] );
    }

    $posts = get_posts( $args );

    if ( ! $posts ) {
        return '';
    }

    $html = '<ul class="wpide-recent-posts">';

    foreach ( $posts as $item ) {
        $date  = 'yes' === $atts['show_date'] ? ' <time datetime="' . esc_attr( get_the_date( 'c', $item ) ) . '">' . esc_html( get_the_date( '', $item ) ) . '</time>' : '';
        $html .= '<li><a href="' . esc_url( get_permalink( $item ) ) . '">' . esc_html( get_the_title( $item ) ) . '</a>' . $date . '</li>';
    }

    return $html . '</ul>';
} );
```

## Notes

Example: [recent_posts number="5" category="news" show_date="yes"].

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Recent Posts Shortcode" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
