I have static front page for my WP installation set from settings > reading. Then I have added a URL endpoint using.

add_rewrite_endpoint('foo', EP_ALL);

So, the front page should be accessible via

http://example.com/
http://example.com/foo
http://example.com/foo/bar

For #1 Everything works fine but for #2 and #3 default home.php is shown instead of static home page. Tested locally in both single and multisite installation.

Is it a desired behavior or I hit something unusual? More importantly how can I make WP to show the static homepage in the given condition?

Solution

I was already hooking into parse_request to process part of code if foo exists. so, as per @gmazzap’s solution. I only need to unset it afterwards. No need for extra hooked function is needed to bypass the bug.

add_action('parse_request', function(&wp){

    $key = 'foo';

    if (!array_key_exists( $key, $wp->query_vars ) ) {
        return;
    }

    // do things when foo exists

    // we no longer need 'foo'
    unset($wp->query_vars[$key]);

});

2 s
2

Maybe I did not get this very well, but if you need to just remove 'foo' from query vars would not be much more simple to use the 'request' filter and remove the var from there?

Code needed:

add_filter('request', function($query_vars) {
     return array_diff_key($query_vars, array('foo'=>''));
});

It:

  • runs on main query only
  • remove the var for $wp object
  • acts before the query is set on $wp_query, so no need to remove the query from there
  • does not affect all the other variables

Edit:

A problem of this code is that it runs very early, so that it will be hard to catch the presence of the query variable and do something based on its presence / value.

A solution may be the run the conditions on the same 'request' filter, just before remove the query var (e.g. using same hook with higer priority).

Another solution may be add a flag to $wp object:

add_filter('request', function($query_vars) {
     $GLOBALS['wp']->_foo = isset($query_vars['foo']) ? $query_vars['foo'] : false;
     return array_diff_key($query_vars, array('foo'=>''));
});

After that, would be possible to check the ‘foo’ variable in any hook fired after 'request', the earliest is 'parse_request'

add_action('parse_request', function($wp) {
    $foo = $wp->_foo;
    // do something with foo
});

The last is 'shutdown':

add_action('shutdown', function() {
    $foo = $GLOBALS['wp']->_foo;
    // do something with foo
});

Leave a Reply

Your email address will not be published. Required fields are marked *