在add_action内执行add_filter还是可以组合它们?



如果产品被添加到购物车中,我需要在页脚添加一个脚本。添加产品后,它将转到结帐页面。因此,在结帐页面上,我需要插入脚本。(只有一次,当添加时。在重新加载页面后,它将不会显示。

add_action( 'wp_footer', 'clearlocal' );
function clearlocal(){
add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {
global $woocommerce;
//Check if product ID is in a certain category
if( has_term( 'packages', 'product_cat', $product_id ) ){
?><script type="text/javascript"> localStorage.clear();
</script><?php
}
//Do nothing with the data and return
return $cart_item_data;
}
}

如果一个产品是从名为packages的类别中添加的,那么我需要添加脚本。但我只在添加时才需要它,而不是总是在产品放入购物车时才需要它。

如果我的目标是显示一条消息。然后它就能按我的要求工作了。

add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {
global $woocommerce;
//Check if product ID is in a certain category
if( has_term( 'packages', 'product_cat', $product_id ) ){
wc_add_notice('Some texts','success');
}
//Do nothing with the data and return
return $cart_item_data;
}

我认为问题是add_filter不与add_action一起工作。我也试过这个,但没有工作。

add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {
global $woocommerce;
//Check if product ID is in a certain category
if( has_term( 'packages', 'product_cat', $product_id ) ){
add_action( 'wp_footer', 'clearlocal' );
function clearlocal(){
?><script type="text/javascript"> localStorage.clear();
</script><?php
}
}
//Do nothing with the data and return
return $cart_item_data;
}

使用wc_enqueue_js

add_filter( 'woocommerce_add_cart_item_data', 'he_check_empty_cart', 10,  3);
function he_check_empty_cart( $cart_item_data, $product_id, $variation_id ) {
//Check if product ID is in a certain category.
if( has_term( 'packages', 'product_cat', $product_id ) ){
wc_enqueue_js(' localStorage.clear();' );
}
}
//Do nothing with the data and return.
return $cart_item_data;
}

最新更新