实时更新产品类别购物车项目计数而无需在 Woocommerce 中重新加载

Live update product category cart item count without reloading in Woocommerce

我创建了一个短代码来计算添加到购物车中属于“72”产品类别的产品数量。

我正在使用此回答线程中的自定义条件函数 has_product_category():

这是我的代码:

function cat_cart_count_bottiglie() {
    $bottiglie = 0; 

    // Iterating through each cart item
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( has_product_category( $cart_item['product_id'], $category_ids = array( 72 ) ) ) {
            $bottiglie += $cart_item['quantity'];
                }
    }
    return $bottiglie;
}
add_shortcode('bottiglie', 'cat_cart_count_bottiglie');

代码运行正常。

但此短代码计数仅在添加到购物车后刷新页面时才会更新,不适用于 Ajax 添加到购物车或在购物车页面中删除商品或更改商品数量时。

有没有办法即时获取更新?

您将需要 javascript 到 运行 对 DOM 的实时更改,但 wordpress 短代码不适用于 ajax(我认为,纠正我如果我错了)。但是,是的,基本上您需要 ajax 再次获取简码或在单击添加到购物车后手动更改 DOM。

以下代码将 Ajax 刷新您的短代码自定义产品类别“72”项计数:

// Custom conditional function that checks also for parent product category terms
function has_product_category( $product_id, $category_ids, $taxonomy = 'product_cat' ) {
    $term_ids = array(); // Initializing

    // Loop through the current product category terms to get only parent main category term
    foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
        if( $term->parent > 0 ){
            $term_ids[] = $term->parent; // Set the parent product category
            $term_ids[] = $term->term_id;
        } else {
            $term_ids[] = $term->term_id;
        }
    }
    return array_intersect( $category_ids, array_unique($term_ids) );
}

// Custom function that count cart items remaining to a product_category
function get_bottiglie_count( $term_ids ){
    $count = 0; // Initializing

    // Loop through each cart item
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( has_product_category( $cart_item['product_id'], $term_ids ) ) {
            $count += $cart_item['quantity'];
        }
    }

    return $count;
}

// Ajax refressing count
add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_bottiglie_count', 50, 1 );
function refresh_bottiglie_count( $fragments ){

    $fragments['#bottiglie-count'] = do_shortcode( "[bottiglie]" );

    return $fragments;
}

// Shortcode that display the count cart items remaining to a product_category
add_shortcode('bottiglie', 'shortcode_bottiglie_count');
function shortcode_bottiglie_count( $atts ) {
    return '<span id="bottiglie-count">' . get_bottiglie_count( array(72) ) . '</span>';
}

代码进入您的活动子主题(活动主题)的 function.php 文件。已测试并有效。