I have a very peculiar requirement, hopefully, I can explain it without being too confusing. I created a page template where I list some properties I get from an external XML file, so far no problems, let’s say the URL is like this:
http://www.example.com/properties/
Each property has a link that should redirect the user to a “Single Property” page that displays more info about it. I was wondering if there’s a way to make the link like this:
http://www.example.com/properties/123
Where 123 would be the id of the property. So if I have the URL like properties/some_id I want to be able to load a view file (like the single.php or page.php files) but specific to this URL condition.
Is this possible?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Add this to your theme’s functions.php, or put it in a plugin.
add_action( 'init', 'wpse26388_rewrites_init' );
function wpse26388_rewrites_init(){
add_rewrite_rule(
'properties/([0-9]+)/?$',
'index.php?pagename=properties&property_id=$matches[1]',
'top' );
}
add_filter( 'query_vars', 'wpse26388_query_vars' );
function wpse26388_query_vars( $query_vars ){
$query_vars[] = 'property_id';
return $query_vars;
}
This adds a rewrite rule which directs requests to /properties/ with any combination of numbers following to pagename properties, with the query var property_id set. Just be sure to visit your permalinks settings page and save to flush rewrite rules, so this new rule will be included.
In your page-properties.php template, get_query_var('property_id') will return the property id if it was set, if it’s not then show the default properties page.
Method 2
Another way to do it:
add_action('init', function() {
add_rewrite_rule( '^properties/([0-9]+)/?',
'index.php?pagename=properties&property_id=$matches[1]',
'top' );
}, 10, 0);
add_action('init', function() {
add_rewrite_tag( '%property_id%', '([^&]+)' );
}, 10, 0);
Codex Rewrite API/add rewrite rule
Codex Rewrite API/add rewrite tag
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0