0

I am using this code to retrieve the category of the current post.

<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>

How could I get the category URL without running another database query?

3

Pass the category id into get_category_link():

<?php
$category = get_the_category();
$link = get_category_link( $category[0]->term_id );
?>

Update Outputting in template:

<?php
$category = get_the_category();
$first_category = $category[0];
echo sprintf( '<a href="%s">%s</a>', get_category_link( $first_category ), $first_category->name );
?>
  • It doesn't run another database query. Everything needed to construct the URL was returned whenever the category was first queried and put into the object cache. I just did a quick test and adding get_category_link didn't increase the number of queries according to Query Monitor. – Jacob Peattie Jul 20 '17 at 12:48
  • ok this looks promising.. i am having trouble putting this together as <a href="$link">$category</a> . could you help please ? – Joanna Mikalai Jul 20 '17 at 13:31
  • I updated by answer. – Jacob Peattie Jul 20 '17 at 13:37
  • No problem. If you can accept my answer that would be swell ;) – Jacob Peattie Jul 20 '17 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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