首页 > 解决方案 > 应用优惠券时在 WooCommerce 结帐页面上添加下拉列表

问题描述

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

当我尝试该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位置

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

标签: jquerywordpresswoocommercecheckoutcoupon

解决方案


在这种情况下,您可以在 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' );

推荐阅读