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 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...
To get category names in WooCommerce, you can use the built-in functions provided by WooCommerce and WordPress. Here's how you can achieve it:First, make sure you have WooCommerce installed and activated on your WordPress site. In your WordPress admin pane...
To get a product name in WooCommerce, you can follow these simple steps:Login to your WooCommerce admin area: Go to your WordPress site's backend and log in using your credentials. Navigate to the "Products" page: Once logged in, click on the "...