0

If I'm on a singular page, it is quite easy to show the current post URL outside the loop:

the_permalink();

If I am on a category page it is quite simple to show the category description outside the loop:

category_description();

Unless I'm missing something, it is not equally easy to show the current category URL outside the loop - which is strange.

echo get_category_link(); - doesn't work like this.

I need to use my category URL in the <head>, for canonical link, og:url etc. How can I do that?

I did read this question and found that you have to create a new function just to show the current category. Is there any other way to do it?

/**
 * Pass in a taxonomy value that is supported by WP's `get_taxonomy`
 * and you will get back the url to the archive view.
 * @param $taxonomy string|int
 * @return string
 */
function get_taxonomy_archive_link( $taxonomy ) {
  $tax = get_taxonomy( $taxonomy ) ;
  return get_bloginfo( 'url' ) . '/' . $tax->rewrite['slug'];
}

1 Answer 1

4

On a category archive, get_queried_object_id() will give you the category's ID, which you can pass to get_category_link():

echo get_category_link( get_queried_object_id() );
1
  • This works! Thank you. You'd be amazed to know that all over the web I have searched, people are creating new functions to show the category url. Your solution is simple and elegant.
    – IXN
    Nov 19, 2017 at 0:46

Your Answer

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

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