Detect category ID using the category slug

Detect category ID using the category slug

Online by JSC0d3
June 6, 2017 | | | 330 recognitions

Sometimes a WordPress Developer needs to know Category ID, I will show you how to find the category ID using the category slug in WordPress.

WordPress is built with nice functions like get_term_by(), and we will use it to get the category ID based on category slug.

What we can do with the get_term_by():

get_term_by( $field, $value, $taxonomy, $output, $filter )
  • $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’

Let’s get practice by adding this code to get category ID based on category slug

$thecatId = get_term_by( 'slug', 'wp', 'category' );
$thecat = $thecatId->term_id;

What’s for this Category ID?

It depends on you, you can use it to add an extra query or display category description.

The next excerpt of code is how to display the category description using the category slug

$thecatId = get_term_by( 'slug', 'wp', 'category' );
$thecat = $thecatId->name;

Of course you can make this code more useful, use your creativity and explore wordpress tricks and create better code to get Category ID based on category slug.

Learn WordPress everyday and you’ll enjoy more with it

JSC0d3's Logo
About JSC0d3

JSC0d3 is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

On the same idea

Posted by | April 1, 2019

Images are vital components of every website Before you start questioning the importance of images, just try to imagine your favorite blog or website...

Posted by | March 5, 2019

I’ve been loosely following the noise and #wpdrama surrounding Gutenberg for as long as it has been around and honestly for the most part I’ve...

Posted by | February 24, 2019

To ensure that your site ranks highly in Search Engine Result Pages (SERPs), you’ll need to make it easy for search engine ‘bots’ to explore...

Previous PostBackNext Post
2 impressions on “Detect category ID using the category slug

James,

It is very useful for me, thanks! I am going to get some more templates for me from and then practice different things on them using your tips and articles here. Thank you again for the help!

StevenMedia,

Awesome! Cheers! 🙂

Leave here an impression