Aggiungere prodotti al carrello di WooCommerce da codice con prezzo custom

Mattepuffo's logo
Aggiungere prodotti al carrello di WooCommerce da codice con prezzo custom

Aggiungere prodotti al carrello di WooCommerce da codice con prezzo custom

In questo articolo abbiamo visto come aggiungere prodotti a WooCommerce attraverso il codice.

In questo articolo vediamo come effettuare questa operazione impostando anche un prezzo custom.

Come prima cosa dobbiamo aggiungere una funzione nel functions.php:

function custom_product_price($cart_object) {
    foreach ($cart_object->get_cart() as $item) {
        if (array_key_exists('custom_price', $item)) {
            $item['data']->set_price($item['custom_price']);
        }
    }
}

add_action('woocommerce_before_calculate_totals', 'custom_product_price');

A questo punto:

$idProdotto = 1;
$prezzo = 23;
WC()->cart->add_to_cart($idProdotto, 1, 0, array(), array('custom_price' => $prezzo));

Enjoy!


Condividi

Commentami!