I have page Example (ID=443, slug=example) that is configured, through Dashboard->Settings->Reading
, as the home page of my WP site. I also have the following rewrite rule configured:
[(example)/(view-section)] => index.php?pagename=$matches[1]&foo=1&bar=2
I have a shortcode in the Example page that should generate content based on presence and value of foo
and bar
query vars. The problem is the query vars are not properly set when I visit the URL /example/view-section
(and others related, see below).
I'm using a test plugin to debug this issue only. The complete code is below:
<!-- language: lang-php -->
<?php
function test_shortcode() {
global $wp_rewrite;
echo '<pre>' . 'foo: ' . get_query_var('foo') . '</pre>';
echo '<pre>' . 'bar: ' . get_query_var('bar') . '</pre>';
echo '<pre>' . print_r($wp_rewrite->rules, true) . '</pre>';
}
add_shortcode('foobar', 'test_shortcode');
function test_rules() {
$rules = get_option('rewrite_rules');
if (!isset($rules['(example)/(view-section)'])) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
add_action('wp_loaded', 'test_rules');
function test_rewrite_rules($wprules) {
$rules = array('(example)/(view-section)' => 'index.php?pagename=$matches[1]&foo=1&bar=2');
return $rules + $wprules;
}
add_action('rewrite_rules_array', 'test_rewrite_rules');
function test_query_vars($query_vars) {
array_push($query_vars, 'foo');
array_push($query_vars, 'bar');
return $query_vars;
}
add_filter('query_vars', 'test_query_vars');
There are three scenarios that gave me different results:
- Going to /example/view-section redirects to / and the query vars values are empty.
- Going to /index.php?pagename=example&foo=1&bar=2 works the way I needed. Showing the content generated by the shortcode and the value of the two query vars passed in the URL.
- If I use
page_id
instead ofpagename
orpage
: /index.php?page_id=443&foo=1&bar=2, thepage_id
query var is removed and the default homepage is shown again.
I would like to know why is WP behaving as described above and, if possible, how to make the first case, at least, work like the second one.
Please note that if the Example page is not configured as the homepage, cases 1 and 3 work as the case 2.
I appreciate your help and will be happy to provide more details if necessary.
EDIT
The question originally included links to a running WP instance with an example of the problem. However, I can't keep that instance running forever, so I removed the links and tried to explain the situation with words only.
flush_rewrite_rules
or$wp_rewrite->flush_rules
, does it?. Also you can see in the results page that the rule is being properly added to$wp_rewrite->rules
array. Thks.