Wordpress - rewrite rules and querystring

You can add your own rewrite rule which will let you tweak the query via URL parameters:

add_action( 'init', 'rewrite_photo_url' );
function rewrite_photo_url() {
    add_rewrite_rule( 'photos/([^/]+)/?$','index.php?page=photos&photo_id=$matches[1]', 'top' );
}

If you need to use a custom variable, i.e. 'photo_id', you have to register the variable so it will be recognized by the query:

add_filter( 'query_vars', 'register_custom_query_vars', 1 );
function register_custom_query_vars( $vars ) {
    array_push( $vars, 'photo_id' );
    return $vars;
}

You can use add_rewrite_tag to register your custom query variable ('id' in question):

add_rewrite_tag('%id%','([0-9]+)');

(The regex tells it only to accepts digits). Then to create your rewrite rule you can use add_rewrite_rule

(both of these should be hooked onto init).

add_rewrite_rule('^photos/([0-9]+)/?','index.php?p=1234&id=$matches[1]','top');

where 1234 is the ID of your 'photos' page. You will need to flush rewrite rules once after adding these (go to the Permalink settings page). Then as @DanielBachhuber says, you can use out get_query_var( 'id' ) to get the ID.

Note, while the regex in the add_rewrite_tag means this will only accept digits - you should probably still sanitize with intval (in any case it may be a string representation of a digit).


Depending on how the rules are being generated, you can use the get_query_var() function to get the value of the 'photo' query var. If it's done properly, 'photo' should be an available query var. You'll need to sanitize the value with intval() or similar of course.