简体   繁体   中英

Enable a custom field placeholder to Woocommerce email subject

In Woocommerce, I have added a custom field to the checkout page using the following code:

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;
}

Now, I would like to include the value that user enters in this field in the 'New Order' woocommerce email subject using {billing_field_newfield} custom placeholder.

However when I go to Woocommerce > Settings > Emails > New Order and put {billing_field_newfield} in the subject, I just get {billing_field_newfield} in the email and not its actual value.

How to add a custom dynamic placeholder to email subject in Woocommerce?

To add a custom active placeholder {billing_field_newfield} in woocommerce email notifications, you will use the following hooked function.

You will check before that _billing_field_newfield is the correct post meta key used to save the checkout field value to the order (check in wp_postmeta database table for the order post_id ) .

The code:

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 );
}

Code goes in function.php file of your active child theme (or active theme). It will works.

Then in Woocommerce > Settings > Emails > "New Order" notification, you will be able to use the dynamic placeholder {billing_field_newfield}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM