add_rewrite_rule() not working

I need to pass a property reference the last part of a URL to search the database for an entry, eg,

http://example.com/cottage-details/G638/

I need to pass the G638 into an array for my plugin. What I have below is calling the cottage-details page, but removing the last part of the URL and showing an empty page, rather than the information I wish to retrieve from the server. If I use

http://example.com/cottage-details/?propref=G638

it works perfectly.

/**
 * Rewrite tags for plugin
 */
function dcc_rewrite_tags() {
    add_rewrite_tag('%propref%', '([^&]+)');
}

add_action('init', 'dcc_rewrite_tags', 10, 0);

/**
 * Rewrite rules for plugin 
 */
function dcc_rewrite_rules() {
    add_rewrite_rule('^[^/]*/([^/]*)/?','index.php?p=2&propref=$matches[1]','top');
}

add_action('init', 'dcc_rewrite_rules', 10, 0);

What’s going on?

1 Answer
1

You rewrite rule is quite broad and will most likely generate a lot of conflicts.

add_action('init', 'dcc_rewrite_tags');
function dcc_rewrite_tags() {
    add_rewrite_tag('%propref%', '([^&]+)');
}

add_action('init', 'dcc_rewrite_rules');
function dcc_rewrite_rules() {
    add_rewrite_rule('^cottage-details/(.+)/?$','index.php?page_id=2&propref=$matches[1]','top');
}

Then you can access to propref query var like:

$propref = get_query_var( 'propref' );

And remember to flush the rewrite rules; you can do it by going to Settings -> Permalinks and clicking on save button.

Note: changed p query var to page_id because, as you said in the comments, you are using a page, not a standard post.

Leave a Comment