Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

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'"
);
share|improve this answer
    
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; } } –  s976 Jul 22 '12 at 11:06
add comment

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

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

     the_content();

     endwhile; endif;
?>

MORE Detail!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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