This is the code I am using:
<?php echo str_replace( home_url(), '', get_permalink($post->ID) ); ?>
What it does is output the permalink as a relative URL i.e. only the slug. For instance, if the permalink is http://example.com/2012/01/post-title/
, the relative URL output by the code would look like /2012/01/post-title/
.
Problem: All Posts and Pages show the right permalink, which is great. But all other pages (including Home, Search and Archives) show the relative URL of the first post and not that of the respective pages. Any idea why? What am I doing wrong here?
Reference: Get page permalink without wpurl
EDIT: Here’s what else I’ve tried:
In functions.php
function get_relative_permalink( $url ) {
$url = get_permalink();
return str_replace( home_url(), "", $url );
}
In header.php
<link rel="alternate" hreflang="en-IN" href="http://in.example.com/<?php echo get_relative_permalink(); ?>" />
Same problem with this as well. But this one shows a not-so-informative error too.