How Do I add a redirect rule to WordPress?

adding these functions should do the trick.

First things first, add this line to functions.php while you are working on this:

add_action('init', 'flush_rewrite_rules');

What that code will do is constantly flush the rewrite rules, it makes this easier to test while you are working on it, instead of having to go in and manually reset them after every little change you make to the rewrite rules.
MAKE SURE you remove this when you are done and satisfied that everything is working.

Next, this function will create the rewrite rules you want.

function custom_add_rewrite_rules( $wp_rewrite ) {
    $new_rules = array( 
        'dynamic/js/(\d+).js' => 'index.php?dynamic=js&jqpostid=' . $wp_rewrite->preg_index(1),
        'dynamic/css/(\d+).css' => 'index.php?dynamic=css&csspostid=' . $wp_rewrite->preg_index(1)
    );
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'custom_add_rewrite_rules');

I took a stab at what maybe the CSS rule would look like as well, you may have to adjust it for your needs, I just figured it would be formatted in a way similar to what you described for the javascript. These may cause some strange behavior when it tries to rewrite the URL into a file extension, and it may not work at all. In that case, just remove the .js and .css from the end of the first part of the associative array entries.

function custom_add_rewrite_rules( $wp_rewrite ) {
    $new_rules = array( 
        'dynamic/js/(\d+)' => 'index.php?dynamic=js&jqpostid=' . $wp_rewrite->preg_index(1),
        'dynamic/css/(\d+)' => 'index.php?dynamic=css&csspostid=' . $wp_rewrite->preg_index(1)
    );
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'custom_add_rewrite_rules');

Basically all this does is sets up the URL to look for and the string it runs in its place. The first part of the array entry has a regular expression that looks for numbers only, the portion in parenthesis. (this can be adjusted to look for a specific number of digits, if needed) The match of which is passed into the second part of the array entry as what will be returned in the string.

I hope this helps you, feel free to contact me if you have any problems.

Leave a Comment