The get_category_by_path() WordPress PHP function retrieves a category based on a URL containing the category slug.
Usage
get_category_by_path($category_path, $full_match = true, $output = OBJECT);
Example:
$categ = get_category_by_path('uncategorized'); printf(__('Category %s', 'textdomain'), $categ->name);
Parameters
$category_path (string)
– Required. URL containing category slugs.$full_match (bool)
– Optional. Whether the full path should be matched. Default: true.$output (string)
– Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Term object, an associative array, or a numeric array, respectively. Default: OBJECT.
More information
See WordPress Developer Resources: get_category_by_path()
Examples
Get a category by slug
In this example, we get a category using the category slug, and display its name.
$categ = get_category_by_path('news'); echo 'Category: ' . $categ->name;
Get a category by partial path
In this example, we get a category by partial path and display its ID.
$categ = get_category_by_path('parent-category/news', false); echo 'Category ID: ' . $categ->term_id;
Get a category as an associative array
In this example, we retrieve a category as an associative array, and display its name.
$categ = get_category_by_path('tech', true, ARRAY_A); echo 'Category: ' . $categ['name'];
Get a category as a numeric array
In this example, we retrieve a category as a numeric array, and display its ID.
$categ = get_category_by_path('business', true, ARRAY_N); echo 'Category ID: ' . $categ[0];
Check for WP_Error
In this example, we retrieve a category and check for a WP_Error object before displaying its name.
$categ = get_category_by_path('nonexistent-category'); if (!is_wp_error($categ)) { echo 'Category: ' . $categ->name; } else { echo 'Error: ' . $categ->get_error_message(); }