Get Category ID using Category Name

A handy code snippet to get the ID of a Category by using its name.

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.


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.