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

时间:2018-10-11 07:42:38

标签: php ajax wordpress woocommerce cart

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

我正在通过此答案线程使用自定义条件函数has_product_category():
Set item quantity to multiples of “x” for products in a specific category in Woocommerce

这是我的代码:

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添加到购物车或在购物车页面中删除项目或更改项目数量时,此短代码计数才会更新。

有没有一种方法可以立即获取更新?

2 个答案:

答案 0 :(得分:1)

以下代码将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文件中。经过测试,可以正常工作。

答案 1 :(得分:0)

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