I have built website for real estate with a fairly typical property search functionality that returns property listings on a property search page.
When a visitor clicks on a listing in the search results, I need to pass the property’s ID to a WP page "property-detail" (that calls a template called template-propertydetail.php) which then uses the ID to pull property data from a database.
So what I need is for a clicked link like:
https://example.com/property-detail/?mlsid=12345
to be rewritten to this when the page displays:
https://example.com/property-detail/12345
UPDATE
I have implemented the code suggested by Moishy below in functions.php and flushed rules and cache but the url does not rewrite.
function custom_rewrite_rule() {
add_rewrite_rule(
'^property-detail/([^/]+)/?$',
'index.php?template_page=property_detail&mlsid=$matches[1]',
'top', 'top'
);
}
add_action('init', 'custom_rewrite_rule');
function add_query_vars_filter( $vars ){
$vars[] = "template_page";
$vars[] = "mlsid";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
function include_custom_template($template){
if(get_query_var('template_page') && get_query_var('template_page') === 'property_detail'){
$template = get_template_directory() ."/templates/template-propertydetail.php";
}
return $template;
}
add_filter('template_include', 'include_custom_template');
2
Answers
and then you can pull the id in the template page:
and to pull your custom template:
Make sure to flush your cache and rewrite rules after adding it by going to Settings > Permalinks and hit ‘Save Changes’
You could also use WP built-in post system. No need for custom rewrite rules or query variables.