Wordpress - 使像/ fr / something这样的URL显示与/ something完全相同

时间:2015-10-18 17:15:46

标签: php wordpress

我希望我的wordpress网站的每个网址与/fr/something完全相同,但显示与/something完全相同的网页。我想保留网址。

我认为我很接近,我用过:

add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_filter( 'query_vars','my_insert_query_vars' );
add_action( 'init','my_flush_rules' );

// flush_rules() if our rules are not yet included
function my_flush_rules(){
    $rules = get_option( 'rewrite_rules' );

    if ( ! isset( $rules['fr(\/(.*))?$'] ) ) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();

    }
}

// Adding a new rule
function my_insert_rewrite_rules( $rules )
{
    $newrules = array();
    $newrules['fr(\/(.*))?$'] = 'index.php?pagename=$matches[1]';
    return $newrules + $rules;
}


// Adding the id var so that WP recognizes it

function my_insert_query_vars( $vars )
{
    array_push($vars, 'id');
    return $vars;
}

它适用于某些网址但不是全部:

/fr/ =>相同细

/fr/page-d-example shows the same/page-d-example =>罚款

/fr/2015/09/25/bonjour-tout-le-monde/重定向到/2015/09/25/bonjour-tout-le-monde/ =>没罚款

你知道为什么最后一个是重定向以及如何防止它?

1 个答案:

答案 0 :(得分:-2)

function lang_support() {
    return array('en','fr'); // Add your support lang-code (1st place is a default)
}

function rewrite_lang(){
    $langs = lang_support();
    foreach($langs as $lang) {
        add_rewrite_endpoint($lang,EP_PERMALINK|EP_PAGES|EP_ROOT|EP_CATEGORIES);
    }
}
add_action('init','rewrite_lang');

function lang(){
    global $wp_query;
    $langs = lang_support();
    $lang_r = "";
    foreach($langs as $lang) {
        if(isset($wp_query->query_vars[$lang])) {
            $lang_r = $lang;
            $_SESSION['lang'] = $lang_r;
        }
    }
    if(in_array($lang_r,$langs)) {
        return $lang_r;
    } else {
        return $langs[0];
    }
}

function init_session(){session_start();}
add_action('init','init_session',1);

function lang_session() { // Redirect by JS if session is set
    $url_lang= basename($_SERVER['REQUEST_URI']);
    if(!in_array($url_lang,lang_support()) && isset($_SESSION['lang'])) {
        if(!is_404()) {
          wp_redirect(currentURL().$_SESSION['lang'],301);
          exit;
        }
    }
}
add_action('wp_head','lang_session');

function output_buffer() {ob_start();}
add_action('init','output_buffer');

function currentURL() {
    $pageURL=(@$_SERVER["HTTPS"]=="on")?"https://":"http://";
        if($_SERVER["SERVER_PORT"]!="80"){
            $pageURL.=$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        }else{
            $pageURL.=$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $pageURL;
}