WordPress php function to get multiple categories by slug name?

WordPress has a built in function for retrieving the category id by slug (get_category_by_slug), but it only accepts one value (a string). What if I wanted to get multiple category id’s, how would I pass it an array?

Here’s what I’m using now

header.php

 $catObj = get_category_by_slug( 'slider' );
 //$termObj = get_term_by('slug', 'slider', 'my_custom_taxonomy')
 $catid = $catObj->term_id;

Related posts

Leave a Reply

1 comment

  1. Here’s a drop-in function you can use in your functions.php. It expects an array of category slugs ($catslugs). It creates an empty array, that is filled by a foreach loop using get_category_by_slug. The foreach loop iterates through each value in the array until it finishes. The function then returns the array $catids for your use elsewhere.

    functions.php

    function get_cats_by_slug($catslugs) {
        $catids = array();
        foreach($catslugs as $slug) {
            $catids[] = get_category_by_slug($slug)->term_id; //store the id of each slug in $catids
        }
        return $catids;
    }
    

    Here’s how you’d use it in your header.php for example

    header.php

    $catslugs = array('uncategorized','slider','news','featured');
    $catids = get_cats_by_slug($catslugs);
    

    We create an array ($catslugs) with the category slugs we wish to retrieve, then we create a variable to store the returned value ($catids) of our function. The function is executed and $catids now contains an array of category id’s for use elsewhere.