// Adds the FacetWP query variables to the Polylang hreflang attribute when page is loaded with facet selections.
// Original: <link rel="alternate" href="https://yourdomain.com/en/translated-page/" hreflang="en" />
// Replaced: <link rel="alternate" href="https://yourdomain.com/en/translated-page/?_my_facet=my_facet_choice" hreflang="en" />
// Hook used: https://polylang.pro/doc/filter-reference/#pll_rel_hreflang_attributes
add_filter( 'pll_rel_hreflang_attributes', function( $hreflangs ) {
// Get the current URL
$currentURL = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Parse the URL
$parsedURL = parse_url($currentURL);
// Extract the query string
$queryString = isset($parsedURL['query']) ? $parsedURL['query'] : '';
// Parse the query string to an associative array
parse_str($queryString, $queryParams);
// Get the URL after the question mark
$urlAfterQuestionMark = '';
if ( http_build_query($queryParams) !== '' ) {
$urlAfterQuestionMark = '?' . http_build_query($queryParams);
}
// Loop over $hreflangs array and append the query string to each value
foreach ($hreflangs as $key => $value) {
$hreflangs[$key] = $value . $urlAfterQuestionMark;
}
return $hreflangs;
} );