Question

So I'm using the widget_posts_args filter to pull in my custom post type posts inside the core 'Recent Posts' widget.

Here is the code:

add_filter('widget_posts_args', function() {
    $params['post_type'] = array('post', 'recipe');
    return $params;
});

So with the filter above, it is in fact pulling in all the 'post' and 'recipe' custom post types which is what I want, but...

With the filter, it's pulling in the Blog pages show at most in the 'Reading' section of the settings page which is set at 10 .. but the issue is, that it's completely ignoring the Number of posts to show count inside the widget itself.

enter image description here

If I remove the filter, it goes back to using the number inside the widget but I don't get my 'recipe' custom post types

The widget has 5 posts defined, but it's pulling in 10 posts based on Blog pages show at most - Here is the picture for reference:
enter image description here

Here is the widget with the correct title:
enter image description here

Is there a way that I can define inside the filter that is should use the widget number of posts instead?

Was it helpful?

Solution

The problem is that you're not modifying the existing arguments for the widget, you're replacing them:

add_filter('widget_posts_args', function() {
    $params['post_type'] = array('post', 'recipe');
    return $params;
});

The result of that filter will be:

$params = [
    'post_type' => [ 'post', 'recipe' ]
];

So any other arguments, including the default number of posts, are removed.

This is because you're not accepting the original value into your filter. Your callback function needs to accept this as an argument, so that you can modify and return it:

add_filter('widget_posts_args', function( $params ) {
    $params['post_type'] = array('post', 'recipe');
    return $params;
});

This is how filters work. You use a function that accepts the original value, and returns a new value.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top