Back to site

How to update agent emails based on property status

The example below shows how to change agent email addresses based on property status. The agency below requires separate email addresses for sales and lettings.

// Agent email updater utility
add_action(
    'init',
    function () {
        if ( ! isset( $_GET['wppd_update_agent_email'] ) ) {
            return;
        }

        $sales_statuses    = [ 'For Sale', 'Sale Agreed', 'Sold' ];
        $lettings_statuses = [ 'To Let', 'Let', 'Let Agreed', 'Has Been Let' ];
        $args              = [
            'post_type'      => 'property',
            'post_status'    => 'any',
            'posts_per_page' => -1,
            'fields'         => 'ids',
        ];
        $query             = new WP_Query( $args );
        $updated           = 0;
        foreach ( $query->posts as $property_id ) {
            $status = get_post_meta( $property_id, 'property_status', true );
            if ( in_array( $status, $sales_statuses, true ) ) {
                update_post_meta( $property_id, 'agent_email', 'sales@example.com' );
                $updated++;
            } elseif ( in_array( $status, $lettings_statuses, true ) ) {
                update_post_meta( $property_id, 'agent_email', 'lettings@example.com' );
                $updated++;
            }
        }
        echo '<div style="padding:2em;font-size:1.2em;"><b>Updated agent_email for ' . $updated . ' properties.</b></div>';
        exit;
    }
);

Pagespeed Optimization by Lighthouse.