How to query post like normal search would do. within search.php page

by Yaniv Kossas   Last Updated September 24, 2019 12:08 PM

I have a costume search in a site i am making.

When a user search a certain term, i want to display category list with a count of how many posts are found with in that category.

I thought of a way but i have problems doing it.

  1. in search.php in the loop in have_posts(), i will add a line that check each post's category and create an array with those categories ... and just +1 each time a certain category repeat itself...... problem with that since pagination is in place, it will only find the categories for the current page while the remaining pages stay unaccounted for.

The fix for that is having another wp_query that just use the s term. without the pagination.

Problem with that is i dont know how to query wp for a certain term like a normal search would do. i though of using query_posts somehow but still unclear on how.

Thanks in advanced.

Answers 2

It is easy to get the number of posts in a category...

$qry = new WP_Query(array('cat'=>2));

... but you could very easily have a lot of queries that way. Maybe something like this would help reduce that:

$catid = 1;
$qry = new WP_Query;
$cat_count = array();
if (!isset($cat_count['cat-'.$catid])) {
    $cat_count['cat-'.$catid] = $qry->found_posts;

At least it only runs a query the first time you encounter a category.

April 30, 2013 00:28 AM

This is what i did:

I run another query without pagination like this:

$newQuaryVars = '&posts_per_page=99999999999999&post_type=post';
$posts = query_posts($query_string .$newQuaryVars);
$categoriesList = array();
$categoriesAmounts = array();

Then in the while have posts i did the following:

while ( have_posts() ) : the_post();
    $postCategories = get_the_category();
        foreach($postCategories as $categoryInfo) {
            $categoriesList[$categoryInfo->term_id] = array( 
                'name' => $categoryInfo->name, 
                'url' => get_category_link( $categoryInfo->term_id ), 
                'amount' => $categoriesAmounts[$categoryInfo->term_id]['amount']

Now i basically have an array with categories name / url and the amount of posts that fit the search term within the that category.

after that i just array_multisort it and displayed it.

Hope that helps anyone out there.

Yaniv Kossas
Yaniv Kossas
April 30, 2013 03:54 AM

Related Questions

WP Query Relations / Compare

Updated March 14, 2017 00:08 AM

Infinite scoll on search page not working

Updated June 07, 2015 12:03 PM

Sorting search results with custom dropdown

Updated March 09, 2018 16:08 PM