get_category_by_slug()
Retrieve category object by category slug.
Uses: get_term_by(), _make_cat_compat()
1 time — 0.000684 sec (slow) | 50000 times — 18.52 sec (slow) | PHP 7.0.2, WP 4.4.2
No Hooks.
Return
Object|false
. Category data object on success, false if not found.
Usage
get_category_by_slug( $slug );
- $slug(string) (required)
- The category slug.
Examples
#1 Get the category ID by passing its slug to the function
$cat = get_category_by_slug( 'category-name' ); if( $cat ){ $id = $cat->term_id; }
The variable $cat will contain the following data:
// category ID $cat->cat_ID // Category name $cat->cat_name // Alternative category name $cat->category_nicename // Category description (set on the category editing page) $cat->category_description // ID of the parent category $cat->category_parent // Number of posts in the category $cat->category_count
#2 What the returned object looks like
$cat = get_category_by_slug( 'codex' ); /* WP_Term Object ( [term_id] => 37 [name] => Codex [slug] => codex [term_group] => 0 [term_taxonomy_id] => 37 [taxonomy] => category [description] => This category contains articles [parent] => 3 [count] => 41 [filter] => raw [term_order] => 1 [cat_ID] => 37 [category_count] => 41 [category_description] => This category contains articles [cat_name] => Codex [category_nicename] => codex [category_parent] => 3 ) */
Changelog
Since 2.3.0 | Introduced. |
get_category_by_slug() get category by slug code WP 6.7.2
function get_category_by_slug( $slug ) { $category = get_term_by( 'slug', $slug, 'category' ); if ( $category ) { _make_cat_compat( $category ); } return $category; }