Search code examples
wordpressseowpml

How to format hreflang from "en-ae" to "en-AE" (WordPress+Rank Math+WPMLl)?


I need to set it by the technical task. I've found only

function hrefs_to_uppercase($hrefs) {  
    $hrefs = array_change_key_case($hrefs,CASE_UPPER);
    return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );

But it makes all characters uppercase - "EN-AE". Tried manually in wpml settings- didn't help


Solution

  • You can simply replace the array key with the following code:

    function hrefs_to_uppercase($hrefs) {  
        $hrefs['en-AE'] = $hrefs['en-ae'];
        unset($hrefs['en-ae']);
        return $hrefs;
    }
    add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
    

    if you want to make every array key have an uppercase second part (e.g. from en-us to en-US), you can use the codes below (assumed all your keys have a similar structure like en-us):

    function hrefs_to_uppercase($hrefs) {  
        foreach ($hrefs as $key => $val) {
            $key_tokens = explode('-', $key);
            $new_key = $key_tokens[0] . '-' . strtoupper($key_tokens[1]);
            $hrefs[$new_key] = $hrefs[$key];
            unset($hrefs[$key]);
        }
        return $hrefs;
    }
    add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );