1. Docs
  2. Developer Guide
  3. Miscellaneous and Snippets
  4. Creating SEO Friendly Property Details URLs

Creating SEO Friendly Property Details URLs

Note: Once the below code is added to your functions.php file you'll need to visit 'Settings > Permalinks' and just click 'Update' to force the rewrite rules to take effect.

add_filter( 'post_type_link', 'customise_property_post_type_link', 10, 4 );
function customise_property_post_type_link( $post_link, $post, $leavename, $sample )
{
    if ( get_post_type($post->ID) == 'property' )
    {
        $property = new PH_Property($post->ID);

        $suffix = 'for-sale';
        if ( $property->department == 'residential-sales' )
        {
            $suffix = 'to-rent';
        }

        $area = $property->address_three;
        if ( $area == '' )
        {
            $area = $property->address_four;
        }
        if ( $area == '' )
        {
            $area = $property->address_two;
        }

        $post_link = str_replace("/property/", "/property-" . $suffix . "/" . sanitize_title($area) . "/", $post_link);
    }

    return $post_link;
}

add_action( 'init', 'rewrites_init' );
function rewrites_init()
{
    add_rewrite_rule(
        'property-for-sale/([^/]+)/([^/]+)/?$',
        'index.php?post_type=property&name=$matches[2]',
        'top' );
    add_rewrite_rule(
        'property-to-rent/([^/]+)/([^/]+)/?$',
        'index.php?post_type=property&name=$matches[2]',
        'top' );
}
Was this article helpful to you? Yes No