Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Notify admin of customer address changes - Email the site admin when a customer changes their billing or shipping address in WooCommerce. https://www.damiencarbery.com/2019/09/notify-admin-of-customer-address-changes/
<?php
/*
Plugin Name: Notify admin of customer address changes
Plugin URI: https://www.damiencarbery.com/2019/09/notify-admin-of-customer-address-changes/
Description: Email the site admin when a customer changes their billing or shipping address in WooCommerce.
Author: Damien Carbery
Author URI: https://www.damiencarbery.com
Version: 0.1
*/
add_action( 'woocommerce_after_save_address_validation', 'dcwd_after_save_address', 10, 4 );
function dcwd_after_save_address( $user_id, $load_address, $address, $customer ) {
//error_log( 'User ID: ' . $user_id );
//error_log( 'Load address: ' . var_export( $load_address, true ) );
//error_log( 'Address: ' . var_export( $address, true ) );
//error_log( 'Customer: ' . var_export( $customer, true ) );
// Retrieve any changes.
$customer_original_info = new WC_Customer( $user_id );
$address_changes = array();
$existing_address = array();
if ( 'billing' == $load_address ) {
$address_changes = $customer->get_billing();
$existing_changes = $customer_original_info->get_billing();
//error_log( 'Billing Address: ' . var_export( $address_changes, true ) );
}
else {
$address_changes = $customer->get_shipping();
$existing_changes = $customer_original_info->get_shipping();
//error_log( 'Shipping Address: ' . var_export( $address_changes, true ) );
}
// Create a list of the changes, with a friendly name for each field (e.g. 'Company Name' instead
// of 'company_name') and the old and new values.
$changes_text = array();
foreach ( $address_changes as $field => $value ) {
$changes_text[] = sprintf( '%s from "%s" to "%s"', $address[ $load_address . '_' . $field ][ 'label' ], $existing_changes[ $field ], $value );
}
if ( $changes_text ) {
//error_log( 'Customer changed ' . ucwords( $load_address ). " address fields:\n" . implode( "\n", $changes_text ) );
// Send the email to the admin.
$subject = sprintf( 'Customer address change: %s (%d)', $customer->get_display_name(), $user_id );
$body[] = sprintf( 'Customer %s (ID: %d) changed %s address fields.', $customer->get_display_name(), $user_id, $load_address );
$body[] = '';
$body[] = 'Changes:';
$body[] = '- ' . implode( "\n- ", $changes_text );
wp_mail( get_option( 'admin_email' ), $subject, implode( "\n", $body ) );
}
else {
// It's possible to save the form without changing anything.
error_log( 'No changes were made.' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.