0

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

4
  • When you run /foo/bar/2/ does it redirect at all? Also... have you flushed the caches ;) Commented Apr 14, 2019 at 2:41
  • @ChrisHappy I just re-flushed caches and doing better. But now when I call /foo/bar/527/ I'm just seeing 1 Commented Apr 14, 2019 at 2:43
  • Let us continue this discussion in chat. Commented Apr 14, 2019 at 2:52
  • 1
    The $matches[1] is only going to work for rewrite rules which correspond to the WordPress's index.php file. But in your case, the second parameter for the add_rewrite_rule() doesn't start with index.php, which means the rewrite rule would be written as a "real" Apache rewrite rule in the .htaccess file and not saved into the database. Hence (as you've figured it out), use $1 for "real" rewrite rules. :) Commented May 1, 2019 at 17:49

1 Answer 1

1

This was solved by changing $matches[1] to $1:

// Add rewrite for my_id
function custom_rewrite_basic() 
{
    add_rewrite_rule('^foo/bar/([0-9]+)/?', 'foo/bar/?my_id=$1', 'top');
}

add_action( 'init', 'custom_rewrite_basic' );

And of course flushing cache.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.