I'd like to retrieve the category object from the category name, using the public query variable category_name
, via get_query_var( 'category_name' )
:
$cat = get_query_var( 'category_name' );
There appear to be two methods:
get_category_by_path()
get_term_by()
Using get_category_by_path()
Based on WordPress core code (wp-includes/canonical.php
), I found out that I'd do it this way:
$category = get_category_by_path( $cat );
Using get_term_by()
Now, as I see it, I can also get the category object like this:
$category = get_term_by( 'slug', $cat, 'category' );
Retrieving the Category object
Then use the category object (held by $get_category
variable) like so:
if( $category && !is_wp_error( $category ) ) {
$get_category = $category;
}
// Just an example of what could be done
if( isset($get_category) ) {
echo 'Current category: ' . $get_category->name;
}
What are the differences between the two methods? What advantages does one have over the other, and in what situations should one be used instead of the other?