Here’s one thing you could do. Create a WP_Query object but only include ids:
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
's' => $s,
'fields' => 'ids',
);
$query = new WP_Query( $args );
$post_counts = $query->post_count;
wp_reset_postdata();
By using fields => ids
you’re only returning the IDs. Also, WP_Query already does a count and supplies it as a property: post_count
. Finally, since we are using a WP_Query we need to reset the globals with wp_reset_postdata()
.