В Woocommerce я смог создать настраиваемое мета-поле с кнопкой, которая отправляет электронное письмо, используя существующий код ответа Отправлять настраиваемое электронное письмо при нажатии кнопки оформления заказа WooCommerce. Он отображает следующий метабокс:
Поэтому, когда я нажимаю кнопку, он отправляет электронное письмо, что отлично работает.
Мой вопрос:
Как я могу настроить этот код для отправки настраиваемого электронного письма, поскольку мне нужно отправить только «Тема» (с идентификатором заказа и суммой платежа) на адрес электронной почты, который должен быть в формате: [email protected]
(чтобы он был отправлен на шлюз SMS и доставлен как СМС на мобильное устройство)?
Например:
Электронный адрес: [email protected]
тема: Ваш заказ {order_id} выполнен. Итого: {order_total}. Спасибо
Обновлено
Первая функция является необязательной и отображает обязательное поле оформления заказа для мобильного телефона.
Второй код функции отображает метабокс на страницах редактирования заказа администратора woocommerce с настраиваемой кнопкой, которая запускает действие. При нажатии на SMS-шлюз будет отправлено настраиваемое электронное письмо с:
'smsgateway.com'
.Note: When using
wp_mail()
function, the message is mandatory (if there is no message or an empty one, the email is not sent).
Код:
// 1. Add mandatory billing phone field (and save the field value in the order)
add_filter( 'woocommerce_billing_fields', 'add_billing_mobile_phone_field', 20, 1 );
function add_billing_mobile_phone_field( $billing_fields ) {
$billing_fields['billing_mobile_phone'] = array(
'type' => 'text',
'label' => __("Mobile phone", "woocommerce") ,
'class' => array('form-row-wide'),
'required' => true,
'clear' => true,
);
return $billing_fields;
}
// 2. Send a specific custom email to a SMS gateway from a meta box
// Add a metabox
add_action( 'add_meta_boxes', 'order_metabox_email_to_sms' );
function order_metabox_email_to_sms() {
add_meta_box( 'sms_notification',
__( 'SMS notification', "woocommerce" ),
'order_metabox_content_email_to_sms',
'shop_order', 'side', 'high' );
}
// Metabox content: Button and SMS processing script
function order_metabox_content_email_to_sms(){
global $pagenow;
if ( $pagenow != 'post.php' || get_post_type($_GET['post']) != 'shop_order' )
return; // Exit
if ( ! ( isset($_GET['post']) && $_GET['post'] > 0 ) )
return; // Exit
$order_id = $_GET['post'];
$is_sent = get_post_meta( $order_id, '_sms_email_sent', true );
// Sending SMS
if ( isset($_GET['send_sms']) && $_GET['send_sms'] && ! $is_sent ) {
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Using the billing mobile phone if it exist, or the billing phone if not.
if ( $mobile_phone = $order->get_meta( '_billing_mobile_phone' ) ) {
$phone = $mobile_phone;
} else {
$phone = $order->get_billing_phone();
}
// Email address: Customer mobile phone + @ + sms domain
$send_to = $phone . '@' . 'smsgateway.com';
// Subject with the order ID and the order total amount
$subject = sprintf(
__("Your order number %d with a total of %s is being processed. Thank you.", "woocommerce"),
$order_id, html_entity_decode( strip_tags( wc_price( $order->get_total() ) ) )
);
// Message: It is required (we just add the order number to it).
$message = $order_id;
// Sending this custom email
$trigger_send = wp_mail( $send_to, $subject, $message );
// Displaying the result
if ( $trigger_send ) {
$result = '<span style = "color:green;">' ;
$result .= __( "The SMS is being processed by the gateway." );
// On email sent with success, Mark this email as sent in the Order meta data (To avoid repetitions)
update_post_meta( $order_id, '_sms_email_sent', $trigger_send );
} else {
$result = '<span style = "color:red;">' ;
$result .= __( "Sorry, but the SMS is not processed." );
}
$result .= '</span>';
}
// Displaying the button
$href = '?post=' . $order_id . '&action=edit&send_sms=1';
$send_text = isset($is_sent) && $is_sent ? '<em><small style = "float:right;"> ('. __("Already sent") . ')</small></em>' : '';
echo '<p><a href = "' . $href . '" class = "button">' . __( "Send SMS" ) . '</a>'.$send_text.'</p>';
// Displaying a feed back on send
echo isset($result) ? '<p><small>' . $result . '</small></p>' : false;
}
Код находится в файле function.php активной дочерней темы (или активной темы). Проверено и работает.
Четыре возможности в этом метабоксе:
Once the SMS is sent once, the feature becomes inactive, to avoid any repetitions.
add_action( 'add_meta_boxes', 'add_meta_box_odoslatsms' ); function add_meta_box_odoslatsms() { add_meta_box( 'custom_order_meta_box', __( 'Odoslat SMS' ), 'custom_metabox_content', 'shop_order', 'side', 'high'); }
и function custom_metabox_content(){ $post_id = isset($_GET['post']) ? $_GET['post'] : false; if (! $post_id ) return; // Exit }
Выглядит неплохо, но в каждом случае я получаю: Извините, но SMS не обрабатывается. Это потому, что я создаю заказ вручную из бэкенда? Дело в том, что я использую WooCommerce для управления заказами, где я создаю заказ только из серверной части (без внешнего взаимодействия). Спасибо
Я ищу совета по этому "мета-обновлению", так как я хотел бы иметь возможность отправлять SMS 2-3 раза или иметь возможность установить это значение в этом фрагменте. // On email sent with success, Mark this email as sent in the Order meta data (To avoid repetitions) update_post_meta( $order_id, '_sms_email_sent', $trigger_send ); } else { $result = '<span style = "color:red;">' ; $result .= __( "Chyba, SMS nemohla byt odoslana." );
Не знаю, что происходит, но я потерял свой фрагмент для метабокса ... Могу ли я спросить вас, как создать кнопку для метабокса для выполнения этого действия (для отправки электронной почты)? Вот что я правильно знаю, чтобы появился метабокс: