0

Using the code below, my search returns results from two different CPTs. How can I display the number of results for each CPT before displaying results?

function more_posts_per_search_page( $query ) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ( $query->is_search ) {
            $query->set( array( 'posts_per_page' => 500, 'post_type' => array( 'author', 'book' ) ) );
        }
    }
}
add_action( 'pre_get_posts','more_posts_per_search_page' );
2

First, your callback to pre_get_posts is wrong. That is not the way that set works. If you had debugging enabled, you'd see Notices. It should be:

function more_posts_per_search_page( $query ) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ( $query->is_search ) {
            $query->set('posts_per_page',500);
            $query->set('post_type',array( 'author', 'book'));
        }
    }
}
add_action( 'pre_get_posts','more_posts_per_search_page' );

Second, there is nothing built in that I am aware of that will return those numbers to you, but it isn't hard to do using a WordPress Core function and a PHP one.

$types = wp_list_pluck($wp_query->posts,'post_type');
// var_dump($types); // debugging
$types_count = array_count_values($types);
var_dump($types_count); // your data

That code should be placed in your theme's search.php.

2
  • Perfect as usual. Just enabled debugging on all my sites in progress, thanks for that too. – drake035 Feb 24 '14 at 18:51
  • Well... "perfect" is the target but not always the fact. Thanks for that though :) – s_ha_dum Feb 24 '14 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.