Override cart item price and image in WooCommerce

Viewed 381

I'm working on a plugin where I need to override the price and the image of the product when is added to the cart. So far I was able to change just the price.

Can someone please help me to implement something similar also for the images?

My_Plugin.php

global $woocommerce;

$custom_price = 200;  
$product_id = 2569;
$variation_id = 2697;   
$quantity = 1;      

$cart_item_data = array('custom_price' => $custom_price, 'regular_price' => $regular_price);   
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
$woocommerce->cart->calculate_totals();

functions.php

function woocommerce_custom_price_to_cart_item($cart_object)
{  
    foreach ($cart_object->cart_contents as $key => $value) {
        if (isset($value["custom_price"])) {
            $value['data']->set_price($value["custom_price"]);
        }
    }
}

add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 16 );

Is possible also to add some additional fields to the products when is added to the cart, like: url_file_uploaded, additional_description, etc

Many thanks!

1 Answers

Your code is a bit obsolete since WooCommerce 3 and there are some missing things. Try the following replacement to include also your custom image attachment ID as follows:

In Your file My_Plugin.php:

$custom_price   = 200;
// $regular_price  = 200; // Not needed and not defined (in your code)
$thumbnail_id   = 35; // <=== Here define the post type "attachment" post ID for your image (Image attachment ID)
$product_id     = 2569;
$variation_id   = 2697;
$variation      = array(); // ? | Not defined in your code
$quantity       = 1;      
$cart_item_data = array(
    'custom_price'  => $custom_price, 
    // 'regular_price' => $regular_price,
    'thumbnail_id' => $thumbnail_id, // Here we add the image attachment ID
); 

WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
WC()->cart->calculate_totals();

In functions.php file of your child theme:

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_data_replacement' );
function custom_cart_item_data_replacement( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
       return;

    // Loop through cart items
    foreach ( $cart->cart_contents as $cart_item ) {
        // Custom price
        if( isset($cart_item["custom_price"]) ) {
            $cart_item['data']->set_price($cart_item["custom_price"]);
        }
        // Custom image attachment id
        if( isset($cart_item["thumbnail_id"]) ) {
            $cart_item['data']->set_image_id($cart_item["thumbnail_id"]);
        }
    }
}

It should works.

You can also alter all product properties via the WC_Product setter available methods.

Related