问题描述
我创建了一个函数,用于在结帐页面的付款信息前添加下拉字段。
当我尝试 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 前端使用 checkout 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' );