[WordPress]Oops, customized query vars make front page missing

There is a very strange thing which may be a bug but not fixed yet in WordPress -- If you add a customized query var, it will make the WordPress lost the static front page and directly point to the post river. (As discussed in https://core.trac.wordpress.org/ticket/25143#comment:36)

For example, if our static front page is http://www.example.com/ and we add following code to add a query var named 'lang' hoping that we could get 'lang' from the structure of http://www.example.com/%lang%
function add_custom_page_variables( $public_query_vars ) {
        $public_query_vars[] = 'lang';

        return $public_query_vars;

    }
add_filter( 'query_vars', array($this, 'add_custom_page_variables') );

It doesn't work. get_query_var will return null and what is worse, the front page will lost if we use http://www.example.com/en. Actually, current parse_query will check $_query after it thinks it is a home page and if $_query contains something and is not empty, parse_query will just jump over the 'page_id' part and unable to find the static front page!

How to solve it?
First, get the query var manually.
$this->base_path = parse_url(get_site_url())['path'];
preg_match('@'.$this->base_path.'\/(en|da|zh)\/?$@', $_SERVER['REQUEST_URI'], $matches);                                                                         

$this->qv = $matches[1];

Second, check the page type. If it is not the home page, add the customized query var. if it is the home page,  DON'T ADD IT.
if(empty($this->qv) && rtrim($this->base_path, '/')  != rtrim($_SERVER['REQUEST_URI'], '/')){
    add_filter( 'query_vars', array($this, 'add_custom_page_variables') );

 }

Finally, add the rewrite rules to validate the customized URL.
global $wp_rewrite;
$extra_rule['('.$this->langs_rex.')/?$'] = 'index.php?lang=$matches[1]';
$wp_rewrite->rules = $extra_rule + $wp_rewrite->rules;
$wp_rewrite->flush_rules();

The last but not least, before all of these steps, we must turn off the URL autocompletion function, or the page will be directed to somewhere else. For more details, please refer to the other blog

[WordPress] About the URL autocompletion function in WordPress


评论

此博客中的热门博文

Openwrt路由器上配置shadowsocks透明代理+gfwlist(PAC)

Configure shadowsocks transparent proxy + gfwlist(PAC) on OpenWRT Router

Using Haproxy + shadowsocks (ha + ss) to setup multi ss backend and load balance