T
T
TheMarser2015-07-05 10:45:13
PHP
TheMarser, 2015-07-05 10:45:13

How to create a rewrite rule in Wordpress?

Hello! It is required to create a rewrite rule in the plugin. Trying to understand how it works, I wrote the following code:

add_filter( 'query_vars', 'add_query_vars' );
function add_query_vars( $vars ) {
    $vars[] = 'my_param';
    return $vars;
}

add_action( 'generate_rewrite_rules', 'add_my_rules' );
function add_my_rules() {
        add_rewrite_rule( 'my_param/(\d+)?$', 'index.php?my_param=$matches[1]', 'top' );
}

add_action('wp', "test_cm");
function test_cm(){
  $my_param_value = get_query_var('my_param');
  echo $my_param_value;
}

But this code doesn't work. Tell me, please, what could be the error?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
webpixel, 2015-07-05
@TheMarser

There is an example in CODEX, in my opinion, illustrative:

function custom_rewrite_basic() {
  add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

also add "rules reset" to your plugin:
https://codex.wordpress.org/Function_Reference/flu...
or try on the "Permalinks" settings page to save the settings 1-2 times and check if your rules work.

A
Alex, 2015-07-05
@mr_ko

Try adding flush_rewrite_rules() after add_rewrite_rule and turn off and on the CNC in the admin panel
And to be sure that everything works the code

$my_param_value = get_query_var('my_param');
  echo $my_param_value;

paste in header.php file

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question