WooCommerce Fragment更新项目总数/小计/总计

时间:2019-09-10 00:26:42

标签: ajax woocommerce

我希望Ajax将项目添加到购物车中,并尝试使用以下代码更新WooCommerce片段,以便项目计数,小计和总计保持同步(无需刷新页面)。但是,除了内容计数之外,下面的方法不起作用,但是即使这样也很断断续续。

我想念什么吗?

function ajaxify_fragments( $fragments ) {

    // Update cart count fragment
    $fragments['.cart-items-total td'] = WC()->cart->get_cart_contents_count();

    // Update cart subtotal fragment
    $fragments['.cart-total td'] = WC()->cart->get_cart_subtotal();

    // Update cart total fragment
    $fragments['.cart-total td'] = WC()->cart->get_cart_total();

    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'ajaxify_fragments', 10, 1 );

1 个答案:

答案 0 :(得分:0)

经过一些进一步的研究,我通过将每个片段更新分离为自己的功能来使其工作。另外,使用ob_start()ob_get_clean()

function ajaxify_cart_count_fragments( $fragments ) {

    // Turn on output buffering
    ob_start();

    // Content
    echo '<td data-title="Items">' . WC()->cart->get_cart_contents_count() . '</td>';

    // Update fragment with new content
    $fragments['.cart-items-total td'] = ob_get_clean();
    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'ajaxify_cart_count_fragments', 10, 1 );

function ajaxify_subtotal_fragments( $fragments ) {

    // Content
    echo '<td data-title="Subtotal">' . WC()->cart->get_cart_subtotal() . '</td>';

    // Update fragment with new content
    $fragments['.cart-total td'] = WC()->cart->get_cart_subtotal();
    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'ajaxify_subtotal_fragments', 10, 1 );