The found_posts WordPress PHP filter allows you to modify the number of posts found by a WP_Query instance.
Usage
add_filter('found_posts', 'my_custom_function', 10, 2);
function my_custom_function($found_posts, $query) {
// your custom code here
return $found_posts;
}
Parameters
- $found_posts (int): The number of posts found by the query.
- $query (WP_Query): The WP_Query instance (passed by reference).
More information
See WordPress Developer Resources: found_posts
Examples
Adjusting Found Posts Count
Modify the number of found posts by subtracting a custom offset.
add_filter('found_posts', 'adjust_found_posts_count', 10, 2);
function adjust_found_posts_count($found_posts, $query) {
$offset = 10; // custom offset value
return $found_posts - $offset;
}
Ignoring Sticky Posts
Decrease the number of found posts by the number of sticky posts.
add_filter('found_posts', 'ignore_sticky_posts', 10, 2);
function ignore_sticky_posts($found_posts, $query) {
$sticky_posts = count(get_option('sticky_posts'));
return $found_posts - $sticky_posts;
}
Limiting Found Posts
Limit the number of found posts to a maximum value.
add_filter('found_posts', 'limit_found_posts', 10, 2);
function limit_found_posts($found_posts, $query) {
$max_posts = 50;
return min($found_posts, $max_posts);
}
Custom Post Type Count Adjustment
Adjust the number of found posts for a specific custom post type.
add_filter('found_posts', 'custom_post_type_count_adjustment', 10, 2);
function custom_post_type_count_adjustment($found_posts, $query) {
if ($query->get('post_type') == 'my_custom_post_type') {
return $found_posts - 5;
}
return $found_posts;
}
Exclude Posts From a Specific Category
Decrease the number of found posts by the number of posts in a specific category.
add_filter('found_posts', 'exclude_category_posts', 10, 2);
function exclude_category_posts($found_posts, $query) {
$category_id = 7; // category ID to exclude
$category_posts_count = count(get_posts(['cat' => $category_id]));
return $found_posts - $category_posts_count;
}