The get_category_by_slug() WordPress PHP function retrieves a category object based on the category slug.
Usage
$category_object = get_category_by_slug( 'example-slug' );
Parameters
$slug
(string) – The category slug to search for.
More information
See WordPress Developer Resources: get_category_by_slug()
Examples
Get category ID from slug
Retrieve the category ID using the category slug.
$category_object = get_category_by_slug( 'news' ); if ( $category_object instanceof WP_Term ) { $category_id = $category_object->term_id; echo 'Category ID: ' . $category_id; }
Display category name
Retrieve and display the category name using the category slug.
$category_object = get_category_by_slug( 'sports' ); if ( $category_object instanceof WP_Term ) { echo 'Category name: ' . $category_object->name; }
Display category description
Retrieve and display the category description using the category slug.
$category_object = get_category_by_slug( 'technology' ); if ( $category_object instanceof WP_Term ) { echo 'Category description: ' . $category_object->description; }
Display category count
Retrieve and display the number of posts in a category using the category slug.
$category_object = get_category_by_slug( 'music' ); if ( $category_object instanceof WP_Term ) { echo 'Number of posts in category: ' . $category_object->count; }
Display category link
Retrieve and display the category link using the category slug.
$category_object = get_category_by_slug( 'events' ); if ( $category_object instanceof WP_Term ) { $category_link = get_category_link( $category_object->term_id ); echo 'Category link: ' . $category_link; }