[英]Custom cart count is not updating without reloading in Woocommerce
我有 ajax 腳本排隊,但我似乎無法在不刷新頁面的情況下更新購物車項目數。
職能:
// Add scripts and stylesheets
function startwordpress_scripts() {
wp_enqueue_style( 'reset', get_template_directory_uri() . '/reset.css' );
wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'style', get_template_directory_uri() . '/veggiee.css');
wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js', array(), null, true);
}
function woocommerce_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
$fragments['a.cart-customlocation'] = ob_get_clean();
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat', 10, 3 );
HTML:
<ul>
<li>
<a href="/cart" id="cart_icon"></a></li><li><span class="counter">
<?php echo sprintf ( _n( '%d', '%d', WC()->cart>get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></span></li>
<li id="access"><?php wp_nav_menu( array( 'sort_column' => 'menu_order', 'container_class' => 'menu-header' ) ); ?></li>
</ul>
我已經研究了這個問題,據我所知,籃子總數應該立即更新而無需刷新。
有誰知道我在這里缺少什么?
您的代碼中有一些錯誤和遺漏的東西。 對於標題中的購物車項目計數,以下將解決問題。
1) header.php
文件中的 HTML 代碼:
<ul>
<li>
<a href="/cart" id="cart_icon"></a>
</li>
<li>
<span class="counter" id="cart-count"><?php
$cart_count = WC()->cart->get_cart_contents_count();
echo sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
?></span>
</li>
<li id="access"><?php wp_nav_menu( array( 'sort_column' => 'menu_order', 'container_class' => 'menu-header' ) ); ?></li>
</ul>
2) 您相關的掛鈎函數代碼,用於啟用購物車項目計數Ajax 刷新:
add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_cart_count', 50, 1 );
function refresh_cart_count( $fragments ){
ob_start();
?>
<span class="counter" id="cart-count"><?php
$cart_count = WC()->cart->get_cart_contents_count();
echo sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
?></span>
<?php
$fragments['#cart-count'] = ob_get_clean();
return $fragments;
}
代碼位於活動子主題(或活動主題)的 function.php 文件中。 測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.