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; ?>" />
zanzan
November 16th, 2014 at 11:49 pm
get_post_type_archive_link( custom-post-type);
this code is ok for one post type.How to do for more post type?
Isabel
November 17th, 2014 at 1:16 pm
I updated this so that you don’t have to manually enter one post type. Now you can use this code as is and it will grab any current post type.
zanzan
November 18th, 2014 at 9:38 pm
thanks
Mike iLL
May 4th, 2016 at 1:06 am
Very helpful. Thank you.
Jen
October 1st, 2016 at 11:28 am
Thank you so much! This was exactly what I needed!
vander2000
December 20th, 2017 at 2:53 am
Thanks for this code
Mostafa Esmaeili
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.