2

I need to add some rewrite rules for my site. I need to link this friendly URL:

www.example.com/site-tool-calendar

to

www.example.com/site-tool?tool=calendar

/site-tool is already a permalink inside WordPress and it is working

I have added the following on my functions.php

function custom_rewrite( $wp_rewrite ) {
    $feed_rules = array(
        '^site-tools-(^/.]+)/$'  =>  'site-tools/?tool=' . $wp_rewrite->preg_index(1),
    );
    $wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
}

add_filter( 'generate_rewrite_rules', 'custom_rewrite' );

Before that, on the functions.php I added the param "tool" to the query vars:

function wpd_query_vars( $query_vars ){
    $query_vars[] = 'tool';
    return $query_vars;
}
add_filter('query_vars', 'wpd_query_vars');

I flushed the rules from the admin Permalink page, and tried to test the URL, but although my rule is being added inside the $wp_rewrite->wp_rewrite_rules() list, it is never matching.

It always match a generic rule that looks like:

([^/]+)(?:/([0-9]+))?/?$

I debugged it and checked that my rule appears at the rules list, at the beginning, but is never executed.

Can anyone help me to double check if I made something wrong? I have tried lot of alternatives and all of them took me to the same situation: the rule appears but is never executed.

2

Please try this.

First add the rewrite rule you need with this function

add_action( 'init', 'rewrite_site_tools_page' );
function rewrite_site_tools_page() {

  add_rewrite_rule(
    '^site-tools-([^/]+)$',
    'index.php?pagename=site-tools&tool=$matches[1]',
    'top');

}

Assuming that page name is site-tools.

Now add the tool as query var

add_filter('query_vars', 'wpd_query_vars');
function wpd_query_vars( $query_vars ){
    $query_vars[] = 'tool';
    return $query_vars;
}

Save permalinks.

Now if you access hxxp://yourdomain.com/site-tools-calculator/ It should work (calculator can be anything else )

If you want to debug it, you can dump the query var "tool" by this function:

add_action('template_redirect', 'test_my_queryvar', 999 );
function test_my_queryvar() {
    die( var_dump( get_query_var( 'tool' ) ) );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.