• Resolved Haja

    (@hajakutbudeen)


    Hello there,

    How to prepend a country code to the beginning of all URLs in WordPress ?

    For example:

    Current URL:
    https://website.com/

    Expected URL:

    https://website.com/sa/
    https://website.com/qa/
    https://website.com/kw/

    I have cookie setup which is store value sa or qa or kw based on geolocation

    • This topic was modified 2 years, 7 months ago by Jan Dembowski.
Viewing 2 replies - 1 through 2 (of 2 total)
  • For this you would have to adjust the permalinks. You can control their processing e.g. here:

    function my_page_rewrite() {
    	add_rewrite_rule('^sa/([^/]*)/?', 'index.php?pagename=$matches[1]', 'top');
    }
    add_action( 'init', 'my_page_rewrite' );

    In this case, a requested page with leading /sa/ in the URL will be processed. Of course, the permalink settings have to be saved again for this.

    BUT: you would have to set these links too, of course, so you would have to adjust the permalink generation (and not only its processing) as well. And here I wonder how you want to do that with your construct?

    Actually, you can also solve such language-specific settings with translation plugins like Polylang.

    Thread Starter Haja

    (@hajakutbudeen)

    Hey threadi,

    Thanks for your replay, your answer really helpful for me to find solution.

    Following code works fine for me,

    default url output:
    https://www.website.com/shop

    public static function rewrite_url() {
        global $wp_rewrite;
        $country = $_COOKIE['country']; // us or ca
        $wp_rewrite->root = "$country/";
        $wp_rewrite->extra_permastructs['product']['struct'] = "$country/product/%product%";
        $wp_rewrite->flush_rules();
    }
    add_action( 'init', 'rewrite_url' );

    new url output:
    https://www.website.com/us/shop
    https://www.website.com/ca/shop

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Prepend a country code to the beginning of all URLs in WordPress’ is closed to new replies.