I have a search result page and I need to show a list of categories with number of posts matching next to them (only categories with posts in results). The keyword must also be searched in the category name. What is the most convenient way to achieve this? Currently I have this:
$results = $wpdb->get_results( '
SELECT COUNT(*) as count
FROM wp_posts
JOIN wp_term_relationships ON wp_posts.id = wp_term_relationships.object_id
JOIN wp_terms ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id
WHERE post_type = "my_type"
AND (
post_content LIKE "%'.mysql_real_escape_string($_GET['s']).'%"
OR post_title LIKE "%'.mysql_real_escape_string($_GET['s']).'%"
OR wp_terms.name LIKE "%'.mysql_real_escape_string($_GET['s']).'%"
)
AND wp_term_relationships.term_taxonomy_id = 8'
If I try to search in posts by category and join only term_relationships, it works but does not includes category names. The long query does not work. What am I doing wrong here?
I'm pretty sure the Default WordPress search includes all posts / post types. If you just want to list your categories on the search page you can use a built in function such as wp_list_categories()
WordPress Codex which has everything you need. If you need to you can create a search template and if you Need even more customization you can use the template tag is_search()
with pre_get_posts()