WooCommerce 订单相关预订的自定义电子邮件主题占位符

Custom email subject placeholders for WooCommerce order related bookings

Woocommerce 提供了将占位符添加到电子邮件主题的选项。我想通过创建一个自定义占位符来扩展该功能,该占位符从 woocommerce 重力表单产品插件和 woocommerce 预订中提取信息。

我已经尝试 代码进行一些更改以查看是否可以正常工作。另外,我尝试获取 woocommerce 元字段,但这也不起作用。

使用此代码我无法获得与订单相关的预订:

// For woocommerce versions up to 3.2
add_filter( 'woocommerce_email_format_string' , 'filter_email_format_string', 20, 2 );
function filter_email_format_string( $string, $email ) {
    // Get the instance of the WC_Order object
    $booking = $get_order;

    // Additional wanted placeholders in the array (find / replace pairs)
    $additional_placeholders = array(
        '{custom_one}'      => $booking->get_start_date(),
    );

    // return the clean string with new replacements
    return str_replace( array_keys( $additional_placeholders ), array_values( $additional_placeholders ), $string );
}

首先你的主要问题是:

如何从订单 (Id) 中获取预订 ID?

由于一个订单可以有很多预订(项目),您可以使用非常简单轻便的 SQL 查询使用 WordPress WPDB Class 和可用的方法。

然后您将能够从此订单的一个预订中获取开始日期并将其设置为电子邮件通知主题的自定义占位符:

// Custom function to get the booking Ids from an order Id (with an SQL query)
function wc_get_booking_ids( $order_id ){
    global $wpdb;

    return $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'wc_booking' AND post_parent =  %d", $order_id ) );
}

// For woocommerce versions up to 3.2
add_filter( 'woocommerce_email_format_string' , 'filter_email_format_string', 20, 2 );
function filter_email_format_string( $string, $email ) {
    if( ! is_a($email->object, 'WC_Order') ) return; // Exit

    $booking_ids = wc_get_booking_ids( $email->object->get_id() );

    if( ! empty($booking_ids) ) {
        // Get the instance of the WC_Booking object from one booking Id
        $booking = new WC_Booking( reset($booking_ids) );

        if( is_a($booking, 'WC_Booking') && method_exists($booking, 'get_start_date') ) {
            // Additional placeholders array (one by line)
            $custom_placeholders = array(
                '{start_date}' => $start_date = $booking->get_start_date(),
            );
            $string = str_replace( array_keys( $custom_placeholders ), array_values( $custom_placeholders ), $string );
        }
    }
    return $string;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。