edrian
edrian

Reputation: 4531

Wordpress - Search and display categories in results (NOT POSTS!)

I have a lot of categories configured on WordPress and I want a way to let the user search (in a free-text input form) for a particular category.

Then, in the results page I only want to list those categories (NOT POSTS!) and show a link to the category page.

It's there a way (or plugin way) to achieve this easily?

UPDATE

And also how about searching for nested categories?, I mean, I have category A with a lot of child categories. It is possible to search for only those child categories (knowing the ID of A)?

UPDATED: SOLUTION

As @AhmadAssaf suggested I ended up making my own query. Here I post the code that I have used in my web:

UPDATED

The JOIN must be done with taxonomies.term_id and not taxonomies.term_taxonomy_id

function getCategories($string) {
    global $wpdb;
    $categories = $wpdb->get_results("
        SELECT terms.term_id, terms.name, taxonomies.description
        FROM wp_terms as terms
        LEFT JOIN wp_term_taxonomy as taxonomies ON taxonomies.term_id = terms.term_id
        WHERE taxonomies.taxonomy = 'category'  && terms.name LIKE '%".$string."%'
        GROUP BY taxonomies.term_id
    ");
    return $categories;
}

Upvotes: 0

Views: 3348

Answers (1)

AhmadAssaf
AhmadAssaf

Reputation: 3664

you can issue a custom mysql query to get all the categories details for a category that its name matches a string you pass

function getCat($string) {
    global $wpdb;
    $cat= $wpdb->get_results("
        SELECT *
    FROM wp__term_relationships
    LEFT JOIN wp__term_taxonomy
       ON (wp__term_relationships.term_taxonomy_id = wp__term_taxonomy.term_taxonomy_id)
    LEFT JOIN wp__terms on wp__term_taxonomy.term_taxonomy_id = wp__terms.term_id
    WHERE wp__term_taxonomy.taxonomy = 'category'  && wp__terms.name LIKE '%".$string."%'
    GROUP BY wp__term_taxonomy.term_id
    ");
return $cat;

}

Upvotes: 3

Related Questions