add_rewrite_rule again

Here’s an example with template_redirect that loads your php script if the prm1 query var is set:

// set up the rewrite
add_action( 'init', 'wpse36736_setup_rewrites' );
function wpse36736_setup_rewrites(){
    add_rewrite_rule( 'snpv/([^/]+)', 'index.php?prm1=$matches[1]', 'top' );
}

// add query var
add_filter('query_vars', 'wpse36736_query_vars');
function wpse36736_query_vars( $query_vars ){
    $query_vars[] = 'prm1';
    return $query_vars;
}

// check the query var on template_redirect
add_filter( 'template_redirect', 'wpse36736_template_redirect' );
function wpse36736_template_redirect(){
    global $wp_query;
    if( $wp_query->get( 'prm1' ) ):
        include( get_template_directory() . "/prm1.php" );
        exit();
    endif;
}

You can then access prm1 in your script via:

$prm1 = get_query_var( 'prm1' );

The only strange thing about this is the way WordPress interprets this query, the behavior in 3.3 seems to be a bit different than with previous versions. If you inspect the global $wp_query variable set for any of these requests, everything is populated as if it’s the main posts page and is_404 is false. I recall this wasn’t the case back when I tried to help out on this question.

Anyway, what I typically do in this situation is create a page, say snpv, and change the rewrite rule to 'index.php?pagename=snpv&prm1=$matches[1]'.

Leave a Comment