get_category_by_slug()
Gets category data by its alternative name (slug).
Uses: get_term_by(), _make_cat_compat()
1 time — 0.004096 sec (very slow) | 50000 times — 4.40 sec (fast) | PHP 8.2.25, WP 6.8.1
No Hooks.
Returns
Object|false. Category data.
Usage
get_category_by_slug( $slug );
- $slug(string) (required)
- Alternative name of the category. The name used in the URL.
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.9
function get_category_by_slug( $slug ) {
$category = get_term_by( 'slug', $slug, 'category' );
if ( $category ) {
_make_cat_compat( $category );
}
return $category;
}