I’m posting this question after looked on every site I found regarding this matter. None of the answers gave me a clue to solve this and google results are contaminated with completely different topics.
What I’m trying to achieve is to display the list of categories of the posts that search query returned.
The final idea is to achieve something like this. (please have in mind that each one of those cities is a category)
User will search for posts, then it goes to results where results are displayed. What I need to do is to find in what categories are all the posts returned in and try to do a post_count on each one of them to show how many posts (of all returned) are within that specific category.
Thanks in advance.
As you have not provided any code, I tried in my way.I guess, It is not the best way to achieve it but as of now, you can do in that way.
Here, I have used
PHP
to achieve your desired result.I have used Twenty Fourteen theme’s
search.php
.Here is my code for the
search.php
of Twenty Fourteen theme and you can implement in yoursearch file
:Here in above code, I have done :
Step-1 : Take one blank array to store ID of the posts that are given by the search query.
Step-2 : Push all the IDs in to created blank array with PHP’s
array_push
function. NOTE: Make sure you have put it in awhile loop
to get all theID
.After two steps, now you have an array of all the post IDs.
Step-3 : Take another blank array to store related category name of the post.
Step-4 : Take one variable and give its value to
1
which is useful at the end.(I have taken$k = 1
).Step-5 : Make one
foreach
loop of Post IDs. And get category name of the posts with wordpress functionget_the_category
.It will fetch category based on post ID
.Step-6 : Now its time to use the blank array that we have created for category name.So just
loop
through category name and store name of the category in to an array.Step-7 : Count total names in the category array with PHP’s
array_count_values
function and assign variable to it.(I have used$something
).After step-7, we have an array of category name. Note: Here in this array, there might be duplication of category name.To remove duplication follow next step.
Step-8 : Use PHP’s ‘array_unique’ function to get only unique value from an array.
Step-9 : Make a
loop
of the category name.If you
echo
right now,it will print categories to total number of post times
.So now its right time to use the variable that we have taken before
foreach
loop of post ID($k=1
).Last step : Now make one condition to print all categories at the last post.
So for that I have used
if($k == sizeof($my_category) )
which means that, It will only print when length of an category array equal to the variableK
(In short, in the end).Increase the value of
$k
.Hope it helps you. Ask me If you have any doubt.