对Woocommerce电子邮件主题启用自定义字段占位符

时间:2019-01-03 01:36:12

标签: php wordpress woocommerce placeholder email-notifications

在Woocommerce中,我使用以下代码向结帐页面添加了一个自定义字段:

add_action( 'woocommerce_checkout_fields', 'woo_add_conditional_checkout_fields' );
function woo_add_conditional_checkout_fields( $fields ) {
    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_id = $cart_item['product_id'];
        $fields['billing']['billing_field_newfield'] = array(
            'label'       => __('New Field', 'woocommerce'),
            'placeholder' => _x('', 'placeholder', 'woocommerce'),
            'required'    => true,
            'class'       => array('form-row-wide'),
            'clear'       => false
        );
    }
    return $fields;
}

现在,我想使用{billing_field_newfield}自定义占位符将用户在“新订单” woocommerce电子邮件主题中的此字段中输入的值包括在内。

但是,当我转到Woocommerce>设置>电子邮件>新订单并将{billing_field_newfield}放在主题中时,我只是在电子邮件中得到{billing_field_newfield},而不是它的实际价值。

如何在Woocommerce中向电子邮件主题添加自定义动态占位符?

1 个答案:

答案 0 :(得分:0)

要在woocommerce电子邮件通知中添加自定义活动占位符{billing_field_newfield},您将使用以下挂钩函数。

您将先检查_billing_field_newfield是用于将签出字段值保存到订单(在wp_postmeta数据库表中签入post_id的正确发布元键) )

代码:

add_filter( 'woocommerce_email_format_string' , 'add_custom_email_format_string', 20, 2 );
function add_custom_email_format_string( $string, $email ) {
    // The post meta key used to save the value in the order post meta data
    $meta_key = '_billing_field_newfield';

    // Get the instance of the WC_Order object
    $order    = $email->object;

    // Get the value
    $value = $order->get_meta($meta_key) ? $order->get_meta($meta_key) : '';

    // Additional subject placeholder
    $new_placeholders = array( '{billing_field_newfield}' => $value );

    // Return the clean replacement value string for "{billing_field_newfield}" placeholder
    return str_replace( array_keys( $additional_placeholders ), array_values( $additional_placeholders ), $string );
}

代码进入您的活动子主题(或活动主题)的function.php文件中。它将起作用。

然后在Woocommerce>设置>电子邮件>“新订单”通知中,您将能够使用动态占位符{billing_field_newfield}