I am using WordPress and on the search page I need to grab the number of posts within the category and display it next to the name. Like so
Cat 1 (3)
Cat 2 (1)
Cat 3 (18)
….
Currently I am using the get_categories()
functions which gives you an object and grabbing the count with $cat->count()
. This grabs the total number of posts within the term but I need to grab that count only from the post within the current query. I am using pre_get_posts
to update the query. Anybody know of a way to do this?
Here is my current code block
foreach ( get_categories() as $cat ) {
if ( $cat->parent === 0 ) {
$checked = ( in_array( $cat->slug, $check ) ) ? 'checked' : '';
printf( '<input id="%1$s" %4$s type="checkbox" name="category[%1$s]"><label for="%1$s" >%2$s ( %3$d )</label><br>',
$cat->slug,
$cat->name,
$cat->count,
$checked
);
}
}
Here is my pre_get_posts
action:
add_action( 'pre_get_posts', 'breed_search_query' );
function breed_search_query( $query ) {
$cats = ( isset( $_GET['category'] ) ) ? implode( ',', array_keys( $_GET['category'] ) ) : null;
$search = ( isset( $_GET['s'] ) ) ? sanitize_text_field( $_GET['s'] ) : null;
if ( ! is_admin() && $query->is_main_query() && is_search() ) {
$query->set( 'post_type', 'post' );
$query->set( 'posts_per_page', 8 );
$query->set( 's', $search );
$query->set( 'category_name', $cats );
}
}
Nice and interesting question must say. Unfortunately, you are not going to get this to work with
get_categories
, so you will need another approach here.Here is how we will do it:
Create a very lean custom query to get all the post ID’s from all posts matching the query
Get all the categories attached to a post
Loop through all the posts and the categories within the posts and build an array with the category names as keys and post ID’s as values
Loop through this new array, and display the category name and also count and display the amount of posts for that specific key ( category )
THE CODE:
(NOTE: The following code is untested and needs at leat PHP 5.4+ due to the new array syntax (
[]
))