How can I get category ID by category name?

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.

Related posts

Leave a Reply

2 comments

  1. 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,
    ]);
    
  2. 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!