I cannot get the query rewriting to work as expected. The desired outcome is for requests going to wpsite.com/foo/bar/2/ to be rewritten as wpsite.com/foo/bar/?my_id=2.
functions.php
// Add custom URL parameters
function add_custom_query_var( $vars ){
$vars[] = "my_id";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
// Add rewrite for my_id
function custom_rewrite_basic()
{
add_rewrite_rule('^foo/bar/([0-9]+)/?', 'foo/bar/?my_id=$matches[1]', 'top');
}
add_action( 'init', 'custom_rewrite_basic' );
bar.php
$my_id = filter_input( INPUT_GET, "my_id", FILTER_SANITIZE_NUMBER_INT );
var_dump($my_id);
When I call /foo/bar/?my_id=2 I see 2, when I use /foo/bar/2/, I do not.
Update
After flushing the cache the result improved. However, regardless of the passed parameter (3, 256205), $my_id comes back as 1.
wpsite.com/foo/bar/?my_id=2 shows 2
wpsite.com/foo/bar/2/ shows 1
/foo/bar/2/does it redirect at all? Also... have you flushed the caches ;)/foo/bar/527/I'm just seeing1$matches[1]is only going to work for rewrite rules which correspond to the WordPress'sindex.phpfile. But in your case, the second parameter for theadd_rewrite_rule()doesn't start withindex.php, which means the rewrite rule would be written as a "real" Apache rewrite rule in the.htaccessfile and not saved into the database. Hence (as you've figured it out), use$1for "real" rewrite rules. :)