Dynamic Implementation of Hreflang Attributes (WordPress)
22 January 2025
Hreflang attributes communicate to search engines which language or regional version of a webpage is relevant to the user. This helps to avoid duplicate content issues and improve user experience by directing visitors to the most appropriate page version.
Here we’ll walk through the dynamic implementation of hreflang attributes in WordPress, including a practical PHP code example to simplify your global SEO efforts.
Key Components of Hreflang
- Hreflang Values: Use standardised language and region codes, such as
enfor English orfr-frfor French (France). - x-default: Acts as a fallback for users whose language preferences don’t match specific tags.
- Placement: Hreflang attributes must be inserted into the
<head>section of your HTML or included in the HTTP headers or website sitemap.
Implementing Hreflang Tags Dynamically Using HTML
Step 1: Understand Key Elements
- Hreflang Values: These define the language and region codes for different versions of a page.
- Return Tags: Ensure all hreflang tags reciprocally link alternate pages to one another.
- x-default: Use this as a universal fallback for unmatched language or region preferences.
Step 2: Add Hreflang Tags Dynamically
Insert the dynamic hreflang generation script into the <head> section of your WordPress `header.php` file.
Sample Code
Here is a PHP example for dynamically implementing hreflang attributes.
<!DOCTYPE html>
<html lang="<?php echo esc_attr(get_bloginfo('language')); ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php
global $wp;
$current_url = get_permalink();
// Improved function to check if the page should be noindexed
function is_noindex() {
// Check if WordPress discourages search engines
if (!get_option('blog_public')) {
return true;
}
// Check if any SEO plugins or theme functions have added a noindex meta tag
ob_start();
do_action('wp_head'); // Capture only wp_head() actions, avoiding duplication
$head_content = ob_get_clean();
return strpos($head_content, '<meta name="robots" content="noindex"') !== false;
}
?>
<link rel="canonical" href="<?php echo esc_url($current_url); ?>">
<?php if (!is_noindex()) : ?>
<link rel="alternate" hreflang="en-au" href="<?php echo esc_url($current_url); ?>">
<link rel="alternate" hreflang="x-default" href="<?php echo esc_url($current_url); ?>">
<?php endif; ?>
<?php wp_head(); ?>
</head>
</html>Explanation of the Code
1. HTML Language Attribute
<html lang="<?php echo esc_attr(get_bloginfo('language')); ?>">
- Dynamically sets the
langattribute usingget_bloginfo('language'). - Ensures the correct language code is applied based on the WordPress settings.
- Improves accessibility and SEO by specifying the language of the document.
2. Meta Tags
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- Defines the document character set as UTF-8 to support special characters.
- Adds the viewport meta tag to ensure responsive behavior on mobile devices.
3. Retrieving the Current Page URL
global $wp;
$current_url = get_permalink();
- Uses
get_permalink()to get the current page URL dynamically. - This is more efficient than manually constructing the URL with
$wp->request.
4. The is_noindex() Function
function is_noindex() {
// Check if WordPress discourages search engines
if (!get_option('blog_public')) {
return true;
}
// Check if any SEO plugins or theme functions have added a noindex meta tag
ob_start();
do_action('wp_head'); // Capture only wp_head() actions, avoiding duplication
$head_content = ob_get_clean();
return strpos($head_content, '<meta name="robots" content="noindex"') !== false;
}
Function Purpose:
- Determines whether the page should include a
noindexmeta tag. - Helps prevent indexing of pages that WordPress or SEO plugins have marked as “noindex.”
How It Works:
- Checks WordPress Privacy Settings:
- Uses
get_option('blog_public'). - If the site is set to “Discourage search engines,” it returns
true(noindex enabled).
- Uses
- Captures Output of
wp_head()Without Duplicating It:- Uses
ob_start()to temporarily capture the content generated bywp_head(). - Calls
do_action('wp_head'), which only triggerswp_head()actions (without executingwp_head()twice). - Uses
ob_get_clean()to retrieve the output and search for thenoindexmeta tag.
- Uses
- Returns
trueif a<meta name="robots" content="noindex">tag is found, meaning the page should not be indexed.
5. Canonical Tag
<link rel="canonical" href="<?php echo esc_url($current_url); ?>">
- Specifies the preferred version of the page for search engines.
- Prevents duplicate content issues by consolidating link signals to a single URL.
6. Alternate Language Versions (Hreflang)
<?php if (!is_noindex()) : ?>
<link rel="alternate" hreflang="en-au" href="<?php echo esc_url($current_url); ?>">
<link rel="alternate" hreflang="x-default" href="<?php echo esc_url($current_url); ?>">
<?php endif; ?>
- Adds
hreflang="en-au"to indicate that this page is the Australian English version. - Adds
hreflang="x-default"to provide a fallback version when no other language matches. - Only includes these tags if the page is indexable, preventing search engines from associating
noindexpages with alternate versions.
7. wp_head() Execution
<?php wp_head(); ?>
- Ensures all WordPress plugins and themes can inject necessary scripts, styles, and meta tags into the
<head>section. - It is executed once in this improved version (previously,
wp_head()was unintentionally called twice).
For an in depth breakdown of this script visit our GitHub repository you will find the project Wiki and a second script built to handle bi lingual websites.
Hreflang attributes are HTML tags that specify the intended language and regional targeting of a webpage. These tags provide a roadmap for search engines to navigate between language variations of your site.
HTML Tags: Insert <link rel="alternate" hreflang="x" href="URL" /> tags in the <head> section of your webpage. This method is ideal for sites where you can directly edit the HTML and want hreflang attributes to load with the page content.
HTTP Headers: Use HTTP headers to add hreflang attributes for non-HTML files (like PDFs). The server sends hreflang details in the HTTP response header, making this a suitable option for downloadable resources that lack an HTML structure.
Sitemap: Include hreflang annotations in your XML sitemap. This is a scalable and centralised approach for websites with multiple pages and languages. It allows you to manage all hreflang attributes in one location without modifying individual pages.
Final Steps and Best Practice
Validate Implementation
Use the technicalseo.com Hreflang Testing Tool to confirm proper configuration of your hreflang attributes.
Access the Code
For additional WordPress functionality scripts, visit our GitHub Repository.
Best Practices
- Include an
x-defaulttag as a fallback for unmatched regions or languages. - Ensure all hreflang tags reciprocally reference alternate pages.
- Test implementation regularly to maintain SEO efficiency.
For more helpful scripts and WordPress resources, check out our WordPress Functionality GitHub Repository. If you have any questions or need further assistance, feel free to leave a comment below!