Posted on

A tip on wordpress add_rewrite_rule()

When you use add_rewrite_rule() function keep in mind the following:

  • Use it inside some hook, normally inside init hook.
  • It wont work unless you have custom permalinks activated.
  • Flush your permalinks

Show me some snippet

// register a custom parameter
add_filter( 'query_vars', function( $query_vars ) {
     $query_vars[] = 'myparamname';
     return $query_vars;
}, 30, 1 );

// do some action based on the custom param
add_action( 'template_include', function ($template) {

    if (get_query_var('myparamname') === 'someval') {
        return 'some other template';   
    }
        
    return $template;
        
}, 10, 1 );

// apply the rule
add_action( 'init',  function() {

    add_rewrite_rule( 'patata', 'index.php?myparamname=someval', 'top' );

}, 1, 0 );