How to Get Category ID by Category Name in WordPress

How-to-Get-Category-ID-by-Category-Name-in-WordPress
2058 Views
3.2
(156)

If you’re working with WordPress, you may need to get the category ID by its name at some point. This is especially true if you’re customizing a theme or developing a plugin. Fortunately, it’s a relatively easy process, and in this article, we’ll walk you through the steps you need to follow.

Before you can get the category ID, you need to know the name of the category you want to retrieve. To do this, log in to your WordPress dashboard and navigate to Posts > Categories. Once there, look for the name of the category you want to retrieve. Take note of the exact name and spelling of the category, as this will be important later.

Get Category ID by Category Name

Paste this code into the functions.php file

If you wish to retrieve the category id from the category name, use the following code.

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

Then just call the function, passing it your category name as an argument. for instance.

<?php
$category_ID = get_category_id( 'Codexcoach' );
?>

Show Anywhere

<?php
add_action( 'init', 'cxc_show_category_name_by_id_fun_call_back' );
function cxc_show_category_name_by_id_fun_call_back() {
	$category_ID = get_category_id('Codexcoach');
}
?>

Getting the category ID by category name is a straightforward process in WordPress. By using the get_term_by() function and the category object’s ID property, you can quickly retrieve the information you need. This information can be useful when you’re customizing themes or developing plugins, so keep it in mind for your next WordPress project.

How useful was this blog?

Click on a star to rate it!

Average rating 3.2 / 5. Vote count: 156

No votes so far! Be the first to rate this blog.

By Hiren Ghoghari

My name is Hiren Ghoghri and I am from Gujarat. I started blogging in 2020. I am very passionate about writing or telling someone about WordPress Development, Elementor, Themes, Plugins, Advanced PHP and Web Development. Now I am ready to tell you every information related to Full Stack Web Development with the help of Codexcoach.com. Thank you

Leave a comment

Your email address will not be published. Required fields are marked *