Get Permalink on Custom Post Type Archive or Taxonomy pages

On a single post or singular page, you get the permalink like:


the_permalink(); // this echoes
// or 
get_permalink(); // this returns, not echo

Get the permalink for a custom post type archives page:

get_post_type_archive_link( get_query_var('post_type') );

Get the permalink for a custom taxonomy page:

get_term_link( get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

Usage

If you use social media open graph tags, then you’ll recognize this which takes the permalink of any current page:

<meta property="og:url" content="<?php the_permalink(); ?>" />

This will not work for WordPress archive pages. But sometimes, especially when using WordPress as a CMS, we have a need to treat an archive page like a regular page, and we want it to get recognized as a page with a permalink. In those cases, I use this to make sure that the correct URL gets inserted into the og:url tag, whether it’s a single post, page, custom taxonomy archive, or custom post type archive.

<?php 
// instead of permalink:
if ( is_tax() ) { 
	$permalink = get_term_link( get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
}
elseif( is_post_type_archive() ) {
	$permalink = get_post_type_archive_link( get_query_var('post_type') );
}
else {
	$permalink = get_permalink();
}
?>
<meta property="og:url" content="<?php echo $permalink; ?>" />

See more: , ,

We've 7 Responses

  1. April 21st, 2020 at 6:05 pm

    Man, I was struggling for two hours and finally found out the difference between the_permalink and get_permalink. I can breathe now. thank you.

    Mostafa Esmaeili

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]