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.


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 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 ...
To set category images in WordPress, you can follow these steps:Log in to your WordPress dashboard.Navigate to the "Posts" section and click on "Categories".Find the category for which you want to set an image and click on "Edit".On the...
To hide uncategorized categories in WooCommerce, you can follow these steps:Log in to the WordPress admin area of your website.Go to WooCommerce and click on "Products" in the sidebar menu.Click on "Categories" to view the list of available cat...