在 WooCommerce 订单快速查看中显示使用过的优惠券

问题描述

我们使用此代码在订单上显示使用过的优惠券。这工作正常!但现在我们也想在订单快速查看中显示这些信息。

我在这里找到了这个钩子:woocommerce_admin_order_preview_end

所以我试图用这个钩子从下面的代码中改变钩子。但是,快速查看功能根本不起作用。当我们点击“眼睛”打开快速视图时 - 什么也没发生。是不是需要对代码做更多的调整,或者是哪里出了问题?

add_action( 'woocommerce_admin_order_data_after_billing_address','custom_checkout_field_display_admin_order_meta',10,1 );


/**
 * Add used coupons to the order edit page
 *
*/
function custom_checkout_field_display_admin_order_meta($order){

    if( $order->get_used_coupons() ) {
    
        $coupons_count = count( $order->get_used_coupons() );
    
        echo '<h4>' . __('Coupons used') . ' (' . $coupons_count . ')</h4>';
         
        echo '<p><strong>' . __('Coupons used') . ':</strong> ';
        
        $i = 1;
        
        foreach( $order->get_used_coupons() as $coupon) {
            echo $coupon;
            if( $i < $coupons_count )
                echo ',';
            $i++;
        }
        
        echo '</p>';
    }

}

解决方法

尝试使用以下内容来显示管理订单快速查看(预览)中使用的优惠券:

// Add custom order data to make it accessible in Order preview template
add_filter( 'woocommerce_admin_order_preview_get_order_details','admin_order_preview_add_custom_data',10,2 );
function admin_order_preview_add_custom_data( $data,$order ) {
    // Replace '_custom_meta_key' by the correct postmeta key
    if( $coupons = $order->get_used_coupons() ) {
        $data['coupons_count'] = count($coupons); // <= Store the count in the data array.
        $data['coupons_codes'] = implode(',',$coupons); // <= Store the count in the data array.
    }
        

    return $data;
}

// Display The data in Order preview
add_action( 'woocommerce_admin_order_preview_end','custom_display_order_data_in_admin' );
function custom_display_order_data_in_admin(){
    // Call the stored value and display it
    echo '<div><strong>' . __('Coupons used') . ' ({{data.coupons_count}})<strong>: {{data.coupons_codes}}</div><br>';
}

代码位于活动子主题(或活动主题)的functions.php 文件中。未经测试它应该可以工作。

基于:Display custom data on Woocommerce admin order preview

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...