0

In first question : Must or do I have to use .htaccess rather than wp redirect ?

I’m loolink for to use wp_redirect() to redirect website to new permalink structure for language. Is it the good function and solution ?

I use add_filter('rewrite_rules_array', 'my_rewrite_rules', 11); to rewrite permalink and insert region code (fr,en,de,es,etc) just after domain.

Example permalink : https://subdmain.domain.com/en. Both of Subdomain and Domain must be included .

Currently the new permalink structure work only manually. What I use :

function langdb() {
    $atvlg = array('fr','en'); 
    $displang ='';
    foreach($atvlg as $keylang => $valuelang ):
        $displang .= $valuelang;
        $displang .= next($atvlg) ? '|' : ''; 
    endforeach;
    return $displang;
}

function my_rewrite_rules($rules) {

    $listlangs = langdb();
        $new_rules = array();
        $subdomain = 'https://' . $_SERVER['HTTP_HOST'] .'/';
        $new_rules['(?:'.$listlangs.')/?$'] = $subdomain.'index.php';
    
        foreach ($rules as $key => $val) {
            $key = '(?:'.$listlangs.')/?' . $key;
            $new_rules[$key] = $val;
        }
        return $new_rules;
    }
    
    add_filter('rewrite_rules_array', 'my_rewrite_rules', 11);

I detect region code from $_SERVER['REMOTTE_ADDR'] and curl call. From this region code I want to redirect automatically visitor depending on the language provided.

I try this code but it doesn't work:

$visitorlang = strtolower(getusercountrycode());
    function atv_redirect(){
        $atvdomain = $_SERVER['REQUEST_NAME'];
        $currentpage = $_SERVER['REQUEST-URI'];
        if(!is_admin()){
            ob_clean();ob_start();
            wp_redirect($atvdomain.'/'.$visitorlang.$currentpage);
            exit;
        }
    }
    
    add_action( 'template_redirect', 'atv_redirect' );

here is first rewrite rules:

array(122) {
  ["(?:fr|en)/?$"]=>
  string(30) "https://domain.com/index.php"
  ["(?:fr|en)/?^wp-json/?$"]=>
  string(22) "index.php?rest_route=/"

This rules works in htaccess but I don't know how to include subdomain I rewrite rule.

RewriteCond %{HTTP:Accept-Language} ^fr [NC]
RewriteRule ^(index\.php)?$ /fr/$1 [R=302,L]

Once I understood regex I would like to reproduce this htaccess code using wordpress functions to add_rewrite_rule to all wp site generating language depending on $_SERVER['REMOTE_ADDR']. I already got the region name from IP.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.