Lee
Lee

Reputation: 4323

What's the best to get page URL in meta tag in Wordpress?

So far I have the following tag in my header.php file

<link rel="alternate" hreflang="en" href="<?php echo $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; ?>" />

And this seems to work, but it looks ugly to me and I'd like to make it as clean as possible. Will using the_permalink() give the exact same output for every page?

<link rel="alternate" hreflang="en" href="<?php the_permalink(); ?>" />

Upvotes: 0

Views: 694

Answers (1)

vard
vard

Reputation: 4136

If you want to do this with Wordpress functions, you can use home_url() by passing it the return of add_query_arg, which used with an empty array will return a clean version of the current url.

echo home_url(add_query_arg(array()));

the_permalink is not reliable for this as it return the URL of the current post - it'll then not work properly on an archive page (it will return the permalink of the first post of the loop).

If you plan to use this few times, you may want to define a new function in functions.php like this:

function the_current_url() {
  echo home_url(add_query_arg(array()));
}

Then in your template:

<link rel="alternate" hreflang="en" href="<?php the_current_url(); ?>" />

Upvotes: 1

Related Questions