When to use ‘get_category_by_path’ vs. ‘get_term_by’ to get category object from `get_query_var( ‘category_name’ )`?

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:

  1. get_category_by_path()
  2. 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?

1 Answer
1

You’re doing it correct @its_me. The latter, get_term_by() would be the best way, In my opinion , as I believe get_category_by_path uses get_term_by, just prepopulating the taxonomy to be category.

Edit: As I mentioned in my comment, get_category_by_path is much less efficient, since it gets multiple terms,. and then compares the hierarchical path. get_term_by is much better.

Leave a Comment