I have a WordPress website built with Elementor Pro and I've added a custom HTML language selector at the end of each page. The selector has links to different language versions of the current page. For SEO purposes, I want to dynamically generate hreflang tags in the section based on these links.
Language Selector HTML example:
<div class="lang-popup">
<div class="lang-selector">
<div id="langs">
<a id="lang-item-1" class="lang-item" href="https://example.com/en/page1/">
<span class="lang-text">English</span>
</a>
<a id="lang-item-2" class="lang-item" href="https://example.com/de/seite1/">
<span class="lang-text">Deutsch</span>
</a>
<a id="lang-item-3" class="lang-item" href="https://example.com/ar/صفحة1/">
<span class="lang-text">عربي</span>
</a>
</div>
</div>
</div>
I tried to write PHP code to pull these URLs from the language selector and generate hreflang tags, but haven't been able to make it work. My goal is to place this code in the header.php file so that it runs dynamically for each page.
Here is the code I wrote:
<?php
// Dynamically determine the base URL for the current page
$current_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Define the URLs for each language version
$languages = array(
'en' => str_replace(array('/de/', '/ar/'), '', $current_url),
'de' => str_replace('/ar/', '/de/', str_replace(array('/de/', '/ar/'), '', $current_url)),
'ar' => str_replace('/de/', '/ar/', str_replace(array('/de/', '/ar/'), '', $current_url))
);
// Loop through each language and output the hreflang link element
foreach($languages as $lang => $url) {
echo '<link rel="alternate" hreflang="'.$lang.'" href="'.$url.'">' . "\n";
}
// Output the x-default link element
echo '<link rel="alternate" hreflang="x-default" href="' . $languages['en'] . '">' . "\n";
?>
I can not get the links from my language selector in this code.
I appreciate any guidance on how to best approach this issue.
I want to dynamically generate hreflang tags in the section based on these links.
I tried to write PHP code to pull these URLs from the language selector and generate hreflang tags, but haven't been able to make it work. My goal is to place this code in the header.php file so that it runs dynamically for each page.
In the end, I can not get the links from my language selector in this code.
source https://stackoverflow.com/questions/77033415/dynamically-generate-hreflang-tags-in-wordpress-from-language-selector-links-usi
No comments:
Post a Comment