I have a few categories with the same name [some of them are sub-categories]. And I want to get an array of ID's for certain cattegory name. I tried this:

 $term = get_term_by('name', $cat_name, 'category');

but it seems that get_term_by() returns only the first term that match the query.


The only alternative I know of (using core functions) is:

// Get terms whose name begins with "my_name"
get_terms( 'category', array( 'name__like' => 'my_name' ) );

// Get terms whose name contains "my_name"
get_terms( 'category', array( 'search' => 'my_name' ) );

If you need an exact match, you'll have to execute a custom query.

$wpdb->get_results( "SELECT t.*, tt.* FROM $wpdb->terms AS t
    INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
    WHERE tt.taxonomy = 'category' AND t.name = 'my_name'"
  • Thank you very much. Before your answer I did: $id = array(); $args = array( 'hide_empty' => 0, ); $categories = get_categories( $args ); foreach($categories as $c){ if ($c->name == $cat_name){ $id[] = $c->term_id; } } – Shimon S Jul 22 '12 at 11:06

get_cat_ID( $cat_name ) can do the trick! Example:

     $category_id = get_cat_ID('Category Name');
     $q = 'cat=' . $category_id;
     if (have_posts()) : while (have_posts()) : the_post();


     endwhile; endif;

MORE Detail!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.