2

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

8

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.

13
  • Yeah, that's one of the many combinations I've tried. Doesn't work either. I've downloaded this plugin: wordpress.org/plugins/monkeyman-rewrite-analyzer and it's showing that the rule's correct and everything should be okay, but for some reason, it's not.
    – Badger
    Commented Jan 28, 2015 at 9:51
  • It works here. Can you be more specific about "it's not working"? Do you get HTTP error? can not get propref query var? Any other issue?
    – cybmeta
    Commented Jan 28, 2015 at 9:53
  • A vardump() of the array shows it's empty viz: array(2) { ["propref"]=> string(0) "" ["brand"]=> string(2) "ZZ" }
    – Badger
    Commented Jan 28, 2015 at 10:01
  • I can only think I'm not calling it correctly, I'm using $values['propref'] = get_query_var( "propref" );
    – Badger
    Commented Jan 28, 2015 at 10:02
  • 1
    If it is a page, the rewrite rule must use page_id instead or p. See WP Query documentation. I've editred the answer.
    – cybmeta
    Commented Feb 14, 2015 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.