2

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?

0

1 Answer 1

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.

2
  • 2
    Actually, get_category_by_slug uses get_term_by not get_category_by_path, or am I missing something? (github.com/WordPress/WordPress/blob/master/wp-includes/…)
    – its_me
    Commented Nov 21, 2013 at 14:17
  • 1
    Nope, you are correct. Actually 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. Commented Nov 21, 2013 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.