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

时间:2019-03-19 20:41:31

标签: php wordpress woocommerce hook-woocommerce orders

在Woocommerce中,我试图显示一条消息,该消息基于客户在提交订单时选择的付款方式。我有2种付款方式, BACS 支票,我需要为每一种显示不同的消息。

I just found that you can put a message on the page of Thankyou.php

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

1 个答案:

答案 0 :(得分:1)

以下内容将首先将基于支付网关的自定义消息另存为自定义订单元数据(自定义字段)…这将使您可以更轻松地在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>';
}

代码在活动子主题(或主题)的function.php文件中。经过测试,可以正常工作。


PDF发票注释

  

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

由于Woocommerce有许多不同的PDF发票插件,因此您将拥有to read the developer documentation的WooCommerce PDF发票插件,以在PDF发票中显示该自定义消息。