Adding rewrite endpoint breaks static front page

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 Comment