根据WooCommerce订单中的付款方式显示自定义文本



在WooCommerce中,我正在尝试根据客户在提交订单时选择的付款方式显示一条消息。我有两种付款方式, BACS 检查,我需要为每个消息显示其他消息。

我刚刚发现您可以在thynyou.php的页面上输入一条消息

但是,我需要此自定义消息才能出现在订单页面上,还将添加到PDF发票(我正在使用WooCommerce PDF发票插件)

以下将首先根据付款网关作为自定义订单元数据(自定义场)保存自定义消息……这将使您可以在PDF发票中设置此订单自定义字段,并具有很多更轻松(请参阅末尾的注释)

// Save payment message as order item meta data
add_filter( 'woocommerce_checkout_create_order', 'save_custom_message_based_on_payment', 10, 2 );
function save_custom_message_based_on_payment( $order, $data ){
    if ( $payment_method = $order->get_payment_method() ) {
        if ( $payment_method === 'cheque' ) {
            // For Cheque
            $message = __("My custom message for Cheque payment", "woocommerce");
        } elseif ( $payment_method === 'bacs' ) {
            // Bank wire
            $message = __("My custom message for Bank wire payment", "woocommerce");
        }
        // save message as custom order meta data (custom field value)
        if ( isset($message) )
            $order->update_meta_data( '_payment_message', $message );
    }
}

然后,以下将在接收到的订单页面上显示此自定义消息,查看订单页面和电子邮件通知,使用挂钩(不更改模板)::

// On "Order received" page (add payment message)
add_filter( 'woocommerce_thankyou_order_received_text', 'thankyou_custom_payment_message', 10, 2 );
function thankyou_custom_payment_message( $text, $order ) {
    if ( $message = $order->get_meta( '_payment_message' ) ) {
        $text .= '<br><div class="payment-message"><p>' . $message . '</p></div>' ;
    }
    return $text;
}
// On "Order view" page (add payment message)
add_action( 'woocommerce_view_order', 'view_order_custom_payment_message', 5, 1 );
function view_order_custom_payment_message( $order_id ){
    if ( $message = get_post_meta( $order_id, '_payment_message', true ) ) {
        echo '<div class="payment-message"><p>' . $message . '</p></div>' ;
    }
}
// Email notifications display (optional)
add_action( 'woocommerce_email_order_details', 'add_order_instruction_email', 10, 4 );
function add_order_instruction_email( $order, $sent_to_admin, $plain_text, $email ) {
    if( $sent_to_admin )
        return;
    elseif( $text = $order->get_meta('_payment_message') )
        echo '<div style="border:2px solid #e4e4e4;padding:5px;margin-bottom:12px;"><strong>Note:</span></strong> '.$text.'</div>';
}

代码在您的活动子主题(或主题)的功能上启用函数。测试并起作用。


注意PDF发票

stackoverflow上的规则是当时的一个问题,因此,对于一个问题,一个答案,以避免您的问题要过于宽。

由于WooCommerce有许多不同的PDF发票插件,因此您必须阅读WooCommerce PDF发票插件的开发人员文档,以在PDF发票中显示该自定义消息。

最新更新