0

The thing I am trying to achieve is to get data from a third party data source and display each piece of information as if it was a "post" in a WP theme. Now, the WP theme intrinsically works with custom post types and looks for a given property (yes, I am talking realty) by its name. So let's say the property was called "House on the beach", it would go ahead and look for it's slug in the database and if it ends up not finding it, it would automatically redirect to a 404. That's what I would like to prevent, without breaking the whole post system.

Specifically, when a user goes to http://example.com/index.php/property/23451, I would like to handle the parameters myself as opposed to WP automatically searching for the property's slug "23451" in the database and redirecting to 404 upon failure.

I think it has to do with the WordPress loop and WP_Query. It seems to be failing and automatically redirecting to 404. Can I circumvent that action somehow ?

This is the first time I work with Wordpress, so any help would be highly appreciated.

1 Answer 1

0

The simplest way to handle this is to create a page with slug property which will be used to display all properties, and add a rewrite rule to handle requests for property IDs.

// add property_id query var to hold ID of requested property
function wpd_query_var( $query_vars ){
    $query_vars[] = 'property_id';
    return $query_vars;
}
add_filter( 'query_vars', 'wpd_query_var' );

// add rewrite rule to handle requests for specific properties
function wpd_rewrite_rule(){
    add_rewrite_rule(
        'property/([0-9]+)/?$',
        'index.php?pagename=property&property_id=$matches[1]',
        'top'
    );
}
add_action( 'init', 'wpd_rewrite_rule' );

Visit your permalinks settings page to flush rewrite rules after adding this code to your theme's functions.php, or in a plugin.

Then in your page-property.php template, use get_query_var( 'property_id' ); to get the ID of the requested property.

2
  • Hey, thanks, it kind of works but I still have problems. Right now, it uses single-property.php file for the page. If I use your rewrite rule there is no 404, but it will not use the single-property.php file that I would want it to use. Do I need to specify a template for that, or will that work with the single-property.php file ?
    – the_critic
    Commented Jul 2, 2015 at 18:09
  • if you're not using posts for properties, there's no point in using a custom post type. you can just rename single-property.php to page-property.php.
    – Milo
    Commented Jul 2, 2015 at 18:26

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.