Find the Category ID using the Category Slug in WordPress

This is a quick little piece of code that I have been using a lot lately. I needed to get the category ID but all I had to work with was the category slug. Luckily WordPress has a neat little function called get_term_by() which makes it super easy. The function can be used to get a lot more information but for this example I am just going to extract the ID.

The function works like this:


$field: (string) (required) Either ‘slug’, ‘name’, or ‘id’. Default: None
$value: (string|integer) (required) Search for this term value. Default: None
$taxonomy: (string) (required) Taxonomy Name. Default: None
$output: (string) (optional) Constant OBJECT, ARRAY_A, or ARRAY_N. Default: OBJECT
$filter: (string) (optional) default is raw or no WordPress defined filter will applied. Default: ‘raw’
We are going to use it like this to get the ID with the category slug ‘tutorials’:

term_id;
?>

If you insert a print_r() function you can echo out all the information that the get_term_by() function contains. Use something like this and see if there is other information that you might want to extract:


Then all you would have to do is use whichever term your see between those square brackets like so:

description;
?>

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie