1. Home
  2. Docs
  3. Developer Guide
  4. Miscellaneous and Snippet...
  5. 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-lettings' )
        {
            $suffix = 'to-rent';
        }

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

        $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? No Yes

How can we help?