Recent posts widget : how to display only the posts of the current category ?

If you want to display the recent posts of the current category archive, there is a simple solution.

You have to filter the query of the WordPress recent post widget. (one of the built-in widgets).

The filter takes one parameter : the query arguments array.

 

Here is the workflow :

1) in appearance > widget, drag and drop the recent posts widget in the wanted sidebar of the theme

2) copy/paste this code in your functions.php (of your child theme of course ūüėČ )

add_filter( 'widget_posts_args', 'my_widget_posts_args');
function my_widget_posts_args($args) {
	if ( is_category() ) { //adds the category parameter in the query if we display a category
		$cat = get_queried_object();
		return array(
			'posts_per_page' => 10,//set the number you want here 
			'no_found_rows' => true, 
			'post_status' => 'publish', 
			'ignore_sticky_posts' => true,
			'cat' => $cat -> term_id//the current category id
			 );
	}
	else {//keeps the normal behaviour if we are not in category context
		return $args;
	}
}

And that shoud do the trick. There are always useful filters in WordPress!

There is also a filter called ‘widget_title’ that could be filtered if you need to contextualized a bit more. Check out this snippet to filter the widget titles.

This filter is located in wp-includes/default-widgets.php.

23 thoughts on “Recent posts widget : how to display only the posts of the current category ?”

Comments are closed.