I created "email notifier for order tracking" plugin for woocommerce. All works fine and when I save tracking number, it sends an email to customer.
But when I save another field in order page, it sends email again. How can I fix it?
add_action('add_meta_boxes', 'kargo_takip');
function kargo_takip() {
add_meta_box('kargo_takip_meta_box', 'Kargo Takip', 'kargo_takip_meta_box_ekle', 'shop_order', 'side', 'high');
}
function kargo_takip_meta_box_ekle() {
global $post;
$meta_field_data = get_post_meta($post->ID, '_kargo_takip', true) ? get_post_meta($post->ID, '_kargo_takip', true) : '';
echo '
<input type="hidden" name="kargo_takip" value="' . wp_create_nonce() . '">
<p style="border-bottom:solid 1px #eee;padding-bottom:13px;">
<input type="text" style="width:250px;";" name="kargo_takibi" placeholder="' . $meta_field_data . '" value="' . $meta_field_data . '"></p>
';
}
And i am saving track code with this:
add_action('save_post', 'kargo_takip_kaydet', 10, 1);
function kargo_takip_kaydet($post_id) {
if (!isset($_POST['kargo_takip'])) {
return $post_id;
}
$nonce = $_REQUEST['kargo_takip'];
if (!wp_verify_nonce($nonce)) {
return $post_id;
}
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
} else {
if (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
$kargo_takip_no = $_POST['kargo_takibi'];
$order = wc_get_order($post_id);
$useremail = $order->get_billing_email();
update_post_meta($post_id, '_kargo_takip', $kargo_takip_no);
wp_mail($useremail, "Your order picked up", "Your track code: " . $kargo_takip_no);
}
Update 2
To avoid repetitive email notifications each time you save the order, you will have to check that tracking code is not saved yet in database and that submitted tracking code field is not empty.
To allow the tracking code to be changed and emailed, we will compare the saved value to the submitted value as an additional condition (OR) in the if statement, checking that the submitted value is not empty.
I have revisited completely your code:
Code goes in function.php file of the active child theme (or active theme).
Code is tested and works in all possible cases avoiding repetitive email notifications.