# Recent Posts Widget Follows the Current Category

> Makes the classic Recent Posts widget list posts from the same category as the post being read, turning it into a simple related posts list.

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

## Code

```php
add_filter( 'widget_posts_args', function ( $args ) {
    if ( ! is_singular( 'post' ) ) {
        return $args;
    }

    $categories = wp_get_post_categories( get_queried_object_id() );

    if ( $categories ) {
        $args['category__in'] = $categories;
    }

    $args['post__not_in'] = array( get_queried_object_id() );

    return $args;
} );
```

## Notes

On pages other than single posts the widget shows the latest posts as usual.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Recent Posts Widget Follows the Current Category" 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/
