如何在WooCommerce中添加产品时只运行一次脚本?



当产品添加到购物车中时,页面转到结帐页面。

在结帐页面上,我只想在添加某个类别的产品时向页脚添加一次脚本。我的意思是,当重新加载页面时,它不会显示。

如果我使用wc_add_notice,它显示一次消息,当重新加载页面时,它不显示。就像我想要的,但add_action( 'wp_footer');不工作。

add_filter('woocommerce_add_to_cart', 'my_woocommerce_add_to_cart', 8, 6);
function my_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
global $woocommerce;
$clearstorage_cat = 30;
$_categorie = get_the_terms($product_id, 'product_cat');
if ($_categorie) {
$in_cart = false;
foreach ($_categorie as $_cat) {
$_lacats = $_cat->term_id;
if ($_lacats === $clearstorage_cat ){
$in_cart = true;
}
}
}

if ( $in_cart ) {  
function clearlocals(){        
?>
<script type="text/javascript">localStorage.clear();</script>
<?php 
add_action( 'wp_footer', 'clearlocals' );
}
}
}

如果我添加一个消息,它就像我想要的那样工作。

if ( $in_cart ) {  
wc_add_notice('Some texts','success');
}

在本例中,消息在添加时只在结帐页面上显示一次。

我想在产品添加到购物车时清除本地存储。

您可以使用相同的通知概念。WooCommerce会话。

在"AddToCart"中设置会话值行动钩。

add_action('woocommerce_add_to_cart', 'my_woocommerce_add_to_cart', 8, 6);
function my_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
global $woocommerce;
$clearstorage_cat = 30;
$_categorie = get_the_terms($product_id, 'product_cat');
if ($_categorie) {
$in_cart = false;
foreach ($_categorie as $_cat) {
$_lacats = $_cat->term_id;
if ($_lacats === $clearstorage_cat ){
WC()->session->set( 'clear_locals, true );
}
}
}

然后检查wp_footer动作钩子,如果它是结帐页面和会话变量设置。

add_action( 'wp_footer', 'checkout_clear_locals_script' );
function checkout_clear_locals_script() {
// Check if checkout page and session variable is set.
if ( is_checkout() && ! is_null( WC()->session->get( 'clear_locals', null ) ) ) {
// Clear the session variable and print the script in footer.
WC()->session->set( 'clear_locals', null );
?>
<script type="text/javascript">localStorage.clear();</script>
<?php
}
}

最新更新