Adding product to cart programatically in woocommerce - woocommerce

I'm adding products via ajax using a function in functions.php that looks like this:
function es_add_to_cart()
{
global $woocommerce;
$product_id = $_GET['product_id'];
$woocommerce->cart->add_to_cart( $product_id );
die ( /*returns updated shopping cart */ );
}
This works and the item gets added but only if the cart already contains an item, this leads me to believe that I need to check if there is already a cart and create a new cart if there isn't. I can't find anything on this in the docs however.

Here is the solution to this problem, running $woocommerce->cart->maybe_set_cart_cookies(); after adding any items, so the same function looks like this:
function es_add_to_cart()
{
global $woocommerce;
$product_id = $_GET['product_id'];
$woocommerce->cart->add_to_cart( $product_id );
$woocommerce->cart->maybe_set_cart_cookies();
die ( /*returns updated shopping cart */ );
}

Related

Price in the shopping cart [duplicate]

I am trying to change product price in cart using the following function:
add_action( 'woocommerce_before_shipping_calculator', 'add_custom_price'
);
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = 400;
}
}
It was working correctly in WooCommerce version 2.6.x but not working anymore in version 3.0+
How can I make it work in WooCommerce Version 3.0+?
Thanks.
Update 2021 (Handling mini cart custom item price)
With WooCommerce version 3.0+ you need:
To use woocommerce_before_calculate_totals hook instead.
To use WC_Cart get_cart() method instead
To use WC_product set_price() method instead
Here is the code:
// Set custom cart item price
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
function add_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 | optional)
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_price( 40 );
}
}
And for mini cart (update):
// Mini cart: Display custom price
add_filter( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 3 );
function filter_cart_item_price( $price_html, $cart_item, $cart_item_key ) {
if( isset( $cart_item['custom_price'] ) ) {
$args = array( 'price' => 40 );
if ( WC()->cart->display_prices_including_tax() ) {
$product_price = wc_get_price_including_tax( $cart_item['data'], $args );
} else {
$product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
}
return wc_price( $product_price );
}
return $price_html;
}
Code goes in functions.php file of your active child theme (or active theme).
This code is tested and works (still works on WooCommerce 5.1.x).
Note: you can increase the hook priority from 20 to 1000 (or even 2000) when using some few specific plugins or others customizations.
Related:
Set cart item price from a hidden input field custom price in Woocommerce 3
Change cart item prices based on custom cart item data in Woocommerce
Set a specific product price conditionally on Woocommerce single product page & cart
Add a select field that will change price in Woocommerce simple products
With WooCommerce version 3.2.6, #LoicTheAztec's answer works for me if I increase the priority to 1000.
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
I tried priority values of 10,99 and 999 but the price and total in my cart did not change (even though I was able to confirm with get_price() that set_price() had actually set the price of the item.
I have a custom hook that adds a fee to my cart and I'm using a 3rd party plugin that adds product attributes. I suspect that these WooCommerce "add-ons" introduce delays that require me to delay my custom action.

How do I get upsell for variable product in Woocommerce?

Short version: How do I get upsell for variable product in Woocommerce?
Longer version:
I need the product ids for upsells.
My old code contains depracated code:
$upsells = $product->get_upsells(); // $product is instace of WC_Product_Variable::
The call should be the following:
$upsells = $product->get_upsells_ids(); // $product is WC_Product::
But a different class.
I tried to get the parent instance using wc_get_product($product->get_parent_id()) - but fail.
So, given the instance of WC_Product_Variable how do I get to the parent method WC_Product::$product->get_upsells_ids() ??
Thanks
The get_upsells-ids() method does not exist. Try get_upsell_ids().
The following code will show you all the upsell ids for the product you are currently visiting:
// quick test to check upsell ids
add_action( 'woocommerce_before_single_product', 'echo_upsell_ids' );
function echo_upsell_ids() {
global $product;
$product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
$product = wc_get_product( $product_id );
$upsell_ids = $product->get_upsell_ids();
echo '<pre>' . print_r( $upsell_ids, true ) . '</pre>';
}
I have tested the code and it works. The snippet goes into your child theme's functions.php file.

Woocommerce add to cart with custom price

I've seen many examples of adding an item to the WC cart with a customer price, but none dynamically. I am trying to do in a shortcode function that receives a POST variables....
if (isset($_POST['wmnf_add_donation'])) {
global $woocommerce;
$cart_object = $woocommerce->cart;
$custom_price = ($_POST['donation_amount'] > 0 ? $_POST['donation_amount'] : 0);
$target_product_id = 65986;
$cart_object->add_to_cart($target_product_id, "1");
foreach ( $cart_object->cart_contents as $key => $value ) {
if ( $value['product_id'] == $target_product_id ) {
$value['data']->price = $custom_price;
}
}
}
This adds the item to the cart of course, but the price is zero and I realize I need to somehow save this array back to the WC cart data. Is this method even possible or can it only be done via a filter or action hook? If so, how can I save the changed array back to the cart contents or make it work to add the one item with its posted price? Any guidance greatly appreciated.
Thanks for that answer doublesharp, I was not able to get it to work as described because the form was posting to the page with my shortcode, which has my form, instead of posting directly to the cart. The $_POST was not being seen and the product ended up zero. I did find another approach, but having a problem using wp_redirect. I changed the above shortcode to this:
if (isset($_POST['wmnf_add_donation'])) {
global $woocommerce;
$custom_price = ($_POST['donation_amount'] > 0 ? $_POST['donation_amount'] : 0);
$target_product_id = 65986;
$_SESSION['donation_amount'] = $custom_price;
$woocommerce->cart->add_to_cart($target_product_id, "1");
wp_redirect( site_url() . '/gifts/swag-bag/');
}
Then I added the following filters to functions.php:
add_filter('woocommerce_get_price','donation_price', 10, 2);
add_filter('woocommerce_get_regular_price','donation_price', 10, 2);
add_filter('woocommerce_get_sale_price','donation_price', 10, 2);
function donation_price($price, $productd){
if($productd->id == '65986'){
$price = $_SESSION['donation_amount'];
}
return $price;
}
This does not work except when wp_redirect is commented out, hence, not redirecting. The above redirects to the cart, but its empty. If I comment out the wp_redirect line and then manually go to the cart, the product is there with my custom price. Actually, I would like to apply a custom price and redirect directly to the checkout page instead of the cart, if possible?
You can use the woocommerce_before_calculate_totals action hook to modify the contents of the cart, including the product prices.
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals' );
function before_calculate_totals( $_cart ){
// loop through the cart_contents
foreach ( $_cart->cart_contents as $cart_item_key => &$item ) {
// you will need to determine the product id you want to modify, only when the "donation_amount" is passed
if ( $item['id'] == 65986 && isset( $_POST['donation_amount'] ) ){
// custom price from POST
$custom_price = $_POST['donation_amount'] > 0 ? $_POST['donation_amount'] : 0;
// save to the cart data
$item['data']->price = $custom_price;
// new versions of WooCommerce may require (instead of line above)...
// $item['data']->set_price($custom_price);
}
}
}

Adding extra info to order

I am programmatically adding a product to the cart. Besides this, somehow, I want to store some extra info (an array) to the order. When the client finishes the order, I want to access that info through some WordPress actions. I'll have to do this immediately after adding the product to the cart, because the info may change after that, if the user doesn't finish the order right away. Is there any way I can do it, without putting the database to work?
You should probably use the WooCommerce Cart Item Meta API and the WooCommerce Order Item Meta API.
You use them like this:
// Add to cart item
// This is triggered on add to cart
add_filter('woocommerce_add_cart_item_data', 'my_add_cart_item_data', 10, 2);
function my_add_cart_item_data( $cart_item_meta, $product_id ) {
//Here we can easily filter what values should be added to what products using the $product_id
$cart_item_meta['my_meta_key'] = 'meta value';
return $cart_item_meta;
}
// Add to order item when the cart is converted to an order
// This is triggered when the order is created
add_action('woocommerce_add_order_item_meta', 'my_order_item_meta'), 10, 2);
function my_order_item_meta( $item_id, $values, $cart_item_key ) {
// The value stored in cart above is accessable in $values here
woocommerce_add_order_item_meta( $item_id, 'meta_key', $values['my_meta_key'] );
//Or add what ever you want
$meta_value = 'value';
woocommerce_add_order_item_meta( $item_id, 'meta_key', $meta_value );
}
I hope that helps.

Prevent WooCommerce brand from being sellable

Hi there we have an online store running on WooCommerce and using the WooCommerce brands plugin (http://docs.woothemes.com/document/wc-brands/) but there is one brand that we are allowed show online with price but not allowed to actually sell.
Is there a function I can add for this particular brand to functions.php that will change the add to cart button in category or widget layout to "more info" and link to the product and then on the product page instead of the add to cart section just have a text message saying to call the store.
You can filter WooCommerce's is_purchasable method. Any item that returns false will not be able to be purchased.
function so_26378581_purchasable( $purchasable, $product ){
if ( has_term( 'your-brand', 'product_brand', $product->id ) ){
$purchasable = false;
}
return $purchasable;
}
add_action( 'woocommerce_is_purchasable', 'so_26378581_purchasable', 10, 2 );
This uses conditional logic to test whether the $product in question has the your-brand term in the product_brand taxonomy... via the has_term() function.
By the way, this is not the type of functionality that belongs in functions.php. Your theme should only be concerned with display/appearances. I would recommend that you make this its own plugin, or add to to a site specific snippets plugin.
to me it made no error message, but it did not work, as applied in my test subject and stand continues with two products of different brands.
I put this code:
function so_26378581_purchasable( $purchasable, $product ){
if ( has_term( 'product_brand', 'product_brand', $product->id ) ){
$purchasable = false;
}
return $purchasable;
}
add_action( 'woocommerce_is_purchasable', 'so_26378581_purchasable', 10, 2 );

Resources