Tricky URL rewrite with custom values in url

As I mentioned in your other question, you don’t want to be touching the .htaccess file, you need an internal rewrite.

So, given the URL:

http://mysite.com/image/wp_username/3digitnumber

we need to add the following rule to handle it:

// set up the rewrite rule
function wpa73374_setup_rewrites(){
    add_rewrite_rule(
        'image/([^/]+)/([0-9]+)/?$',
        'index.php?pagename=custompage&iuser=$matches[1]&iname=$matches[2]',
        'top'
    );
}
add_action( 'init', 'wpa73374_setup_rewrites' );

Note above, we point to a page with slug custompage. You can change that to whatever page slug you are using to handle these custom URLs. If the page is a child page of another, you must add pagename=parentpage/childpage. After adding rewrite rules, be sure to visit the permalinks settings page to flush rewrites so your new rules will begin working.

Now the above alone won’t work though, because WordPress doesn’t know what iuser and iname are, so we need to add those to recognized query vars:

// add your custom query vars
function wpa73374_query_vars( $query_vars ){
    $query_vars[] = 'iuser';
    $query_vars[] = 'iname';
    return $query_vars;
}
add_filter( 'query_vars', 'wpa73374_query_vars' );

Then finally within the template, use get_query_var( 'iuser' ) and get_query_var( 'iname' ) to get your custom query var values.

Leave a Comment