应用优惠券时在 WooCommerce 结帐页面上添加下拉列表

Add dropdown list on WooCommerce checkout page when coupon is applied

我创建了一个函数来在结帐页面的付款信息前添加一个下拉字段。

当我尝试 add_action 函数时,以下内容正在运行。

add_action('woocommerce_review_order_before_payment', 'add_store_selection');
function add_store_selection() {
    
    $content .= '<div id="store-pickup-select">';
    $content .= '<select><option selected="selected">Choose one</option>';
            
        /* Here i will get a list of option value from another function */
    
    $content .= '</select>';
    $content .= '</div>';
    echo $content;
} 

但我需要的是我只希望在应用优惠券代码时显示此下拉菜单。我删除了 add_action('woocommerce_review_order_before_payment', 'add_store_selection');

然后我试了这个:

function add_store_list() {

    do_action( 'woocommerce_review_order_before_payment');

}
add_action( 'woocommerce_applied_coupon', 'add_store_list');

下拉列表显示在结算明细的顶部,而不是 woocommerce_review_order_before_payment 位置

点击优惠券代码后,如何使下拉菜单出现在付款前部分?

在这种情况下,您可以在 WooCommerce 前端使用结帐 JS 事件

$( document.body ).trigger( 'applied_coupon_in_checkout' );
$( document.body ).trigger( 'removed_coupon_in_checkout' );

所以你得到:

function action_woocommerce_review_order_before_payment() {
    $content = '<div id="store-pickup-select">';
    $content .= '<select>';
    $content .= '<option selected="selected">Choose one</option>';
    $content .= '<option value="my-option">My option</option>';
    $content .= '</select>';
    $content .= '</div>';
    
    echo $content;
}
add_action( 'woocommerce_review_order_before_payment', 'action_woocommerce_review_order_before_payment', 10, 0 );

// jQuery code
function action_wp_footer() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) {
    ?>
    <script type="text/javascript">
    jQuery(function($) {
        // Default
        $( '#store-pickup-select' ).hide();
        
        $( document.body ).on( 'applied_coupon_in_checkout removed_coupon_in_checkout', function( event ) {
            // With no parameters, the .toggle() method simply toggles the visibility of elements:
            $( '#store-pickup-select' ).toggle();
        });
    });
    </script>
    <?php
    }
}
add_action( 'wp_footer', 'action_wp_footer' );