How to Detect Category ID using the Category Slug in WordPress

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, this trick is originally by Bavotasan and I rewrote it.

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()

1
<?php 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

1
2
3
4
<?php
$theCatId = get_term_by( 'slug', 'tutorials', 'category' );
$theCatId = $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

1
2
3
4
<?php
$theCatId = get_term_by( 'slug', 'tutorials', 'category' );
$theCatId = $theCatId->description;
?>

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

Leave a Reply

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