简体   繁体   中英

Adding cart item data to woocommerce from custom url link

I have built custom Buy Now button to product archive page, with the following URL structure to add product to cart:

www.mydomain.com/shop/?add-to-cart=30 <-product ID

It works perfect, but I need to use the hook woocommerce_add_cart_item_data and that hook doesn't respond to my URL request.

Here is what I have tried:

// Save the "grams_quantity" custom product field data in Cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_in_cart_the_custom_product_field', 10, 2 );
function save_in_cart_the_custom_product_field( $cart_item_data, $product_id ) {
    if( isset( $_POST['grams_quantity'] ) ) {
        $cart_item_data[ 'grams_quantity' ] = $_POST['grams_quantity'];

        // When add to cart action make an unique line item
        $cart_item_data['unique_key'] = md5( microtime().rand() );
        WC()->session->set( 'custom_data', $_POST['grams_quantity'] );
    }
    return $cart_item_data;
}

That code works fine in single-product.php page, because the button there isn't custom.

Here is how I added my custom field to archive shop products loop:

// Add a product custom field "grams_quantity" that will update the displayed price
add_action('woocommerce_after_shop_loop_item', 'custom_shop_loop', 30);
function custom_shop_loop(){
    
        // get the current post/product ID
        $product_id = get_the_ID();
    
        // get the product based on the ID
        $product = wc_get_product( $product_id );
    
    if( $product->is_type( 'simple' ) ){


    // Only for products under certain category
    if ( ! ( has_term( 'מגשי פירות', 'product_cat', $product_id ) ) ) return;
    ?>
        <div class="grams-field">
            <label for="grams_quantity"><?php _e('גרמים: ','woocoomerce'); ?><span></span><br>
                <input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity" value="100" min="100">
            </label>
        </div><br>

    <?php
    }
}

Right now when I click on Buy Now button, it adding my product to cart without grams_quantity data attribute.

How can I use woocommerce_add_cart_item_data hook correctly in archive shop page?

EDIT:

Codepen

Got it solved by $_GET , not the best solution but it works.

// Add a product custom field "grams_quantity" that will update the displayed price
add_action('woocommerce_after_shop_loop_item', 'custom_shop_loop', 30);
function custom_shop_loop(){
        global $wp;
       // get the "Checkout Page" URL
        $url = home_url( $wp->request );
        
    
        // get the current post/product ID
        $product_id = get_the_ID();
    
        // get the product based on the ID
        $product = wc_get_product( $product_id );
    
    if( $product->is_type( 'simple' ) ){


    // Only for products sold by gram
    if ( ! ( has_term( 'מגשי פירות', 'product_cat', $product_id ) ) ) return;
    ?>
        <style>
            .pewc-total-field{
                display: none;
            }
        </style>
        <div class="grams-field">
            <label for="grams_quantity"><?php _e('גרמים: ','woocoomerce'); ?><span></span><br>
                <input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity<?php echo $product_id; ?>" value="100" min="100">
            </label>
            <span class="custom-price-shop<?php echo $product_id; ?>"></span>
        </div><br>
        <a style="display: block; text-align: center;" href="<?php echo $url; ?>/?add-to-cart=<?php echo $product_id; ?>" class="buy-now button buy-<?php echo $product_id; ?>">קנה עכשיו</a>

        <script type="text/javascript">
            (function($){
                // variables initialization
                var priceByGram = <?php echo $product->get_price(); ?>,
                    currencySymbol = $(".woocommerce-Price-currencySymbol").html(),
                    updatedPrice;
                console.log(priceByGram);
                $(".custom-price-shop<?php echo $product_id; ?>").html('סך הכל: ' + priceByGram * 100 +'&nbsp;'+currencySymbol);

                // On live event: imput number fields
                $('input#grams_quantity<?php echo $product_id; ?>').on("change", function() {
                    if (+$(this).val() > 500) {
                        $("#grams_quantity<?php echo $product_id; ?>").attr('step', 500);
                        $("#grams_quantity<?php echo $product_id; ?>").attr('min', 0);
                        if (+this.value < 1000) this.value = 1000;
                        this.value = Math.round(this.value / 500) * 500;
                    }

                    if (+$(this).val() <= 500) {
                        $("#grams_quantity<?php echo $product_id; ?>").attr('step', 100);
                        $("#grams_quantity<?php echo $product_id; ?>").attr('min', 100);
                        this.value = Math.max(100, Math.round(this.value / 100) * 100);
                    }
                });
                $('input#grams_quantity<?php echo $product_id; ?>').on( "click blur", function(){
                    updatedPrice = ($(this).val() * priceByGram).toFixed(2);
                    $(".custom-price-shop<?php echo $product_id; ?>").html('סך הכל: ' + updatedPrice +'&nbsp;'+currencySymbol);
                });
                $('.buy-<?php echo $product_id; ?>').on("click", function(e){
                    e.preventDefault();
                    $link = $(this).attr("href");
                    $grams = $("#grams_quantity<?php echo $product_id; ?>").val();
                    window.location.href= $link + "&grams=" + $grams;
                });
            })(jQuery);
        </script>
    <?php
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM