在add_action WooCommerce中运行JS函数

问题描述 投票:0回答:1

我在functions.php中有此操作:

add_action( 'woocommerce_before_calculate_totals', 'adding_custom_price', 10, 1);
function adding_custom_price( $cart ) {
global $current_user, $woocommerce, $wpdb;

    // This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

            $quantity = 0;
                foreach ( $cart->get_cart() as $cart_item ) {
                    $quantity += $cart_item['quantity'];
                    $product_id = $cart_item['data']->get_id();
                    $product_price = $cart_item['data']->get_price();
                    $categorie_id = $cart_item['data']->get_category_ids();
                    $korting_product = get_field( 'discount_points', $product_id );

                    //Zet prijs min benegas korting
                    $cart_item['data']->set_price($product_price - $korting_product);
                }

echo "<script type='text/javascript'>alert('$quantity');</script>";

}

但带有此行:

echo "<script type='text/javascript'>alert('$quantity');</script>";

更改数量后,推车保持装载状态,所以我做错了。我没有收到警报。

javascript woocommerce cart product-quantity
1个回答
0
投票

注1:为什么使用JavaScript警报?而不是WooCommerce的内置功能? wc_add_notice( __( 'my message' ), 'error');


注2:除了在循环中添加数量外,您还可以使用$items_in_cart = $cart->get_cart_contents_count();

那么你会得到

function adding_custom_price( $cart ) {
    // This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $quantity = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        $quantity += $cart_item['quantity'];

        $product_id = $cart_item['data']->get_id();
        $product_price = $cart_item['data']->get_price();
        $categorie_id = $cart_item['data']->get_category_ids();
        //$korting_product = get_field( 'discount_points', $product_id );
        // For debugging purposes, REMOVE!
        $korting_product = 5;

        //Zet prijs min benegas korting
        $cart_item['data']->set_price($product_price - $korting_product);
    }

    if ( $quantity > 5 ) {
        wc_clear_notices();
        wc_add_notice( __( $quantity ), 'error');
    }
}
add_action( 'woocommerce_before_calculate_totals', 'adding_custom_price', 10, 1);
© www.soinside.com 2019 - 2024. All rights reserved.