Question

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'];
}
Était-ce utile?

La solution

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() );
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top