Get Category ID From Category Name Function [WordPress]

Working on a new WordPress plugin for a client, I found the need to get a category’s ID from the category’s name.

Surprisingly, I found that there was no WordPress function to accomplish this.

So, here’s the little one I came up with to solve the problem:

	// Function to retrieve category ID, given name -
	function get_category_id($category_name) {
		$term = get_term_by('name', $category_name, 'category');
		return $term->term_id;

Add this into your functions.php file or, if developing a plugin, into your plugin file.

Call it by passing your category name, like:

	// Assign category ID of 'Category Name' to $category_id variable
	$category_id = get_category_id('Category Name');

Leave a Reply