Get Category ID using Category Name

a minute read

There are times when WordPress developers need category data, especially the ID, while developing themes and plugins. It is not an ideal way, but sometimes, you may need to get the category ID using the Category name.

In case you too are in such a situation, here is a quick code snippet to grab the ID of a category by providing the category name.

The Function

We can utilize the get_term_by() function from WordPress core to get the term ID, the term in this case would be our category. The function could be used read the name of term, and to return its ID. Below function executes this idea in just few of lines:

function get_category_id($cat_name){
  $term = get_term_by('name', $cat_name, 'category');
  return $term->term_id;
}

Include this function in your plugin’s main file, or in case if you are implementing it on a theme, add it in the functions.php file of your theme.

Usage

Best practice is to get the returned value from our function in a variable, as shown below:

$category_ID = get_category_id('Code Snippets');

Hope you found it useful.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To create a custom WooCommerce category template, you will need to first create a new PHP file in your theme folder. You can name this file something like "category-custom.php" or any other relevant name.You can then copy the code from the default WooC...
You can get the current product category name in WooCommerce by first getting the current product category ID using the get_queried_object() function. Then, use the get_cat_name() function to retrieve the category name based on the ID. Finally, you can display...
To retrieve all posts by a specific category in WordPress, you can use the built-in function get_posts() along with the WP_Query class. Here's how you can accomplish this:First, you need to find the category ID for the desired category. You can do this by ...