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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.