4

I'm developing a WP plugin and have a WordPress URL:

(e.g.: http://localhost/testsite1/coder/?id=66),

and have attempted to add a rewrite rule to

http://localhost/testsite1/coder/66/

using the following rule:

function add_mypage_rule(){
    add_rewrite_rule(
        '^coder/([0-9]+)',
        'index.php?id=$matches',
        'top'
    );
}

add_action('init', 'add_mypage_rule');

I have registered a WP Query Var using:

add_filter('query_vars', 'registering_custom_query_var');

function registering_custom_query_var($query_vars){
    $query_vars[] = 'id';
    return $query_vars;
}

but when at URL http://localhost/testsite1/coder/66/, when I run code

echo get_query_var('id');

nothing is displayed

however when at URL http://localhost/testsite1/coder/?id=66 the echo statement will display 66.

What is wrong with my rewrite rule resulting in echo get_query_var('id'); not accessing the parameter and displaying 66?

Ruvee
  • 8,611
  • 4
  • 18
  • 44
sw123456
  • 3,339
  • 1
  • 24
  • 42

1 Answers1

4
  1. When you use add_rewrite_rule function, the first argument is the regular expression. Right? When you wrap your regular expression/pattern in parentheses, you're grouping the expression, which means you could access the captured group in the parentheses like this: id=$matches[1].
  • Regular expression ^coder/([0-9]+)
  • Access it in the first captured group (since the id is in the first parenthesis), id=$matches[1]
add_action('init', 'add_mypage_rule');

function add_mypage_rule()
{
    add_rewrite_rule(
        '^coder/([0-9]+)',
        'index.php?id=$matches[1]',
        'top'
    );
}
  1. After that, refresh the permalinks and rewrite rules by navigating to:
    Settings > Permalinks > Click on the 'Save changes' button at the bottom of the page!

And now it should, theoretically, work, unless there are more details that you have not mentioned in your question!


enter image description here

Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • Thank you once again! Much appreciated!! – sw123456 Jan 19 '22 at 06:20
  • One last issue that I wonder if you can help with. When at the new URL `http://localhost/testsite1/coder/66/` the page layout reverts to the global Wordpress template and not to any layout (e.g. full width) changes I made to the original page. Is the page's CSS no longer being accessed and if so do you know the solution? – sw123456 Jan 19 '22 at 06:49
  • Sure, not a problem! As far as the layout goes, you could add/change/modify the layout based on a specific url. You could even add your custom css/javascript based on a specific url. There are multiple ways you could set it up, but I would usually use `template_redirect` hook and couple of conditional checks. There are tons of posts about `template_redirect` hook here on SO. If you find it hard to set this up, then feel free to open up a new question, others and I will try to help you out! – Ruvee Jan 19 '22 at 13:59