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