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?

1 Answer 1

5

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 );
?>
5
  • 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. Commented Jul 20, 2017 at 12:48
  • ok this looks promising.. i am having trouble putting this together as <a href="$link">$category</a> . could you help please ?
    – JoaMika
    Commented Jul 20, 2017 at 13:31
  • I updated by answer. Commented Jul 20, 2017 at 13:37
  • No problem. If you can accept my answer that would be swell ;) Commented Jul 20, 2017 at 14:08
  • Works like a charm on 2023, thanks Commented Jun 26, 2023 at 21:40

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.