4

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.

2 Answers 2

12

Use get_terms(), which uses WP_Term_Query under the hood. For a full list of all the available parameters check out the documentation for WP_Term_Query::__construct

// Get term *IDs* with name that *matches* "my_name"
$term_ids = get_terms([
    'fields' => 'ids',
    'taxonomy' => 'category',
    'name' => 'my_name',
    'hide_empty' => false,
]);

// Get term *objects* with name that *matches* "my_name"
$terms = get_terms([
    'taxonomy' => 'category',
    'name' => 'my_name',
    'hide_empty' => false,
]);

// Get term *objects* with name that *contains* "my_name"
$terms = get_terms([
    'taxonomy' => 'category',
    'name__like' => 'my_name',
    'hide_empty' => false,
]);
1
  • 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, 2012 at 11:06
6

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!

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.