I am attempting to have php check if the cart has 2 items specified from an array before applying a free product and coupon. This specific example I've included is checking the price is over a certain amount. I have tried this because I could not get the two items to work.
function bbloomer_add_gift_if_sku_added_cart( $passed, $product_id, $quantity ) {
global $woocommerce;
$skuswithgift = array('SMWB-M23','001-SLW');
$giftsku = 'comb';
$coupon_code = 'combfree';
$product = wc_get_product( $product_id );
if ($product->get_sku() && in_array($product->get_sku(), $skuswithgift) && $woocommerce->cart->total > 26.00) {
WC()->cart->add_to_cart( wc_get_product_id_by_sku($giftsku) );
wc_add_notice( __( 'Hey there! As promised, you recieved a free comb with the purchase of two towels and we added it to your cart for you!', 'woocommerce' ), 'success' );
$woocommerce->cart->add_discount( $coupon_code );
}
else {
WC()->cart->remove_cart_item( wc_get_product_id_by_sku($giftsku) );
$woocommerce->cart->remove_coupon( $coupon_code );
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'bbloomer_add_gift_if_sku_added_cart', 10, 3 );
Tried this and it's not working
function bbloomer_add_gift_if_sku_added_cart( $passed, $product_id, $quantity ) {
global $woocommerce;
$skuswithgift = array('SMWB-M23','001-SLW');
$giftsku = 'comb';
$coupon_code = 'combfree';
$product = wc_get_product( $product_id );
$total_towels = 0;
// Determine how many towels there are
// Loop through every cart item
foreach ( $woocommerce->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
//$product = $cart_item;
// Is it in Gift SKUs
$is_towel = in_array($product->get_sku(), $skuswithgift);
if($is_towel){
// Add this quantity to the total towels
$total_towels += intval($cart_item['quantity']);
}
}
// Apply Discount
if ($total_towels <= 2) {
WC()->cart->add_to_cart( wc_get_product_id_by_sku($giftsku) );
wc_add_notice( __( 'Hey there! As promised, you recieved a free comb with the purchase of two towels and we added it to your cart for you!', 'woocommerce' ), 'success' );
$woocommerce->cart->add_discount( $coupon_code );
}
else {
WC()->cart->remove_cart_item( wc_get_product_id_by_sku($giftsku) );
$woocommerce->cart->remove_coupon( $coupon_code );
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'bbloomer_add_gift_if_sku_added_cart', 10, 3 );
Try below code
add_action('woocommerce_add_to_cart_redirect','customeApplyCode');
function customeApplyCode()
{
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$productSku = array();
foreach($items as $item => $values) {
// Retrieve WC_Product object from the product-id:
$product = wc_get_product( $values['product_id'] );
// Get SKU from the WC_Product object:
$productSku[] = $product->get_sku();
}
$skuswithgift = array('SMWB-M23','001-SLW');
$result=array_intersect($skuswithgift,$productSku);
if(count($result)>0)
{
//product id of free product
$product_id = 1312;
$woocommerce->cart->add_to_cart($product_id);
add_filter( 'woocommerce_product_needs_shipping', 'hide_shipping_when_free_is_available', 10, 2 );
}
}
function hide_shipping_when_free_is_available( $rates, $package ) {
return false;
}
Related
I am trying to add different product in cart. There are two type of product one is other and another is simple.
I need to grab if simple product in the cart then only simple can added and other in cart then only other.
I don't want to add simple and other type of product simultaneously.
add_action('woocommerce_add_to_cart', 'custome_add_to_cart', 10, 6);
function custome_add_to_cart($cart_id, $product_id, $request_quantity, $variation_id, $variation, $cart_item_data) {
global $woocommerce;
//print_r($cart_item_data); //Current
// die();
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_type = $cart_item['type'];
if ($product_type == 'other'){
if($cart_item_data['type'] == 'other'){
WC()->cart->add_to_cart( $product_id );
// print_r($cart_item); //Old Cart
// die();
}else{
wc_print_notice( 'This type of product not added 1', 'notice' );
}
}else{
//print_r($cart_item); //Old Cart
if($cart_item_data['type'] != 'other'){
WC()->cart->add_to_cart( $product_id );
}else{
wc_print_notice( 'This type of product not added 2', 'notice' );
exit;
}
}
}
}
}
I am using this hook but it's not working for me. It show 503 error.
Instead of using woocommerce_add_to_cart use woocommerce_add_to_cart_validation
This filter returns $passed, $product_id, $quantity, $variation_id, $variations but we need only the type of product.
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_to_cart_validationcustom', 10, 2 );
function woocommerce_add_to_cart_validationcustom( $passed, $product_id ) {
global $woocommerce;
if(WC()->cart->is_empty()) return true;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$current_type = $product->get_type();
}
//Get the product we are adding as object
$product_to_add = wc_get_product( $product_id );
$type_to_add = $product_to_add->get_type();
// Check if the product type is the same
if ( $current_type !== $type_to_add){
wc_add_notice( sprintf( __( "This is my custom error", "your-theme-language" ) ) ,'error' );
return false;
} else {
return true;
}
}
I have this code to show when the product is already in the cart I need it to show the quantity of the product also.
add_filter( 'woocommerce_product_add_to_cart_text', 'wcpt_modify_add_to_cart_text', 9999, 2 );
function wcpt_modify_add_to_cart_text( $text, $product ) {
// if cart is empty return 'Add to Quote'
if ( WC()->cart->is_empty() ) return 'Add to Quote';
// otherwise loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
$qty = $cart_item['quantity'];
// if cart contains current product ID return its quantity
if ( $product->get_id() == $product_id ) {
return $qty . ' - Already Added';
}
}
// if the cart is not empty but the product is not in the cart...
return 'Add to Quote';
}
UPDATED CODE ABOVE UPDATED WITH HOOKS ASWELL
The Code Above works wonders thanks to #businessbloomer the only problem now is that I have to refresh the page to see anything
Code is a bit messy, this revised version should work. I added some inline comments to explain each new section:
add_filter( 'woocommerce_product_add_to_cart_text', 'wcpt_modify_add_to_cart_text', 9999, 2 );
function wcpt_modify_add_to_cart_text( $text, $product ) {
// if cart is empty return 'Add to Quote'
if ( WC()->cart->is_empty() ) return 'Add to Quote';
// otherwise loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
$qty = $cart_item['quantity'];
// if cart contains current product ID return its quantity
if ( $product->get_id() == $product_id ) {
return $qty . ' - Already Added';
}
}
// if cart is not empty but product is not in the cart...
return 'Add to Quote';
}
Screenshot:
I want to add automatically one variations product into cart when cart total is become more than 25. The automatically adding variation product price need to set as 0 and also customers cant change the qty or need to disable the Qty filed for free product. I added below code and its working fine only the issue when page reloading or cart updating the the Qty of free product is increasing every time.I only want to sell 1 qty of free product. How to do that ? Code is following below.
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 25;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( ! is_admin()) {
$free_product_id = 2696;
$variation_id = 2697;
$arr = array();
$arr['Color'] = 'Blue';// Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id,1,$variation_id,$arr );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id,1,$variation_id,$arr );
}
}
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
function add_custom_price( $cart_object ) {
$cart_total = 25; // If cart total is more than this value.
$free_product_id = 2697; // Set price to 0 of this free product.
$carttotal = 0;
foreach ( $cart_object->cart_contents as $key => $value ) {
$_product = $value['data'];
if ( $_product->get_id() == $free_product_id ){
continue;
}
$carttotal += $value['line_total'];
}
if ( $carttotal >= $cart_total ) {
$custom_price = 0; // This will be your custome price
foreach ( $cart_object->cart_contents as $key => $value ) {
$_product = $value['data'];
if ( $_product->get_id() == $free_product_id ){
$value['data']->set_price( $custom_price );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
add_filter( 'woocommerce_quantity_input_args', 'hide_quantity_input_field', 20, 2 );
function hide_quantity_input_field( $args, $product ) {
// Here set your product IDs in the array
$product_ids = array(2697);
// Handling product variation
$the_id = $product->is_type('variation') ? $product->get_variation_id() : $product->get_id();
//var_dump($the_id);
// Only on cart page for a specific product category
if( is_cart() && in_array( $the_id, $product_ids ) ){
$input_value = $args['input_value'];
$args['min_value'] = $args['max_value'] = $input_value;
}
return $args;
}
Try adding below code in the functions.php and replace with required product id
add_filter( 'woocommerce_add_to_cart_validation', 'allowed_products_variation_in_the_cart', 10, 5 );
function allowed_products_variation_in_the_cart( $passed, $product_id, $quantity, $variation_id, $variations) {
$product_b = 14091;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$cart_product_id = $cart_item['product_id'];
if ($cart_item['variation_id']) {
$cart_product_id = $cart_item['variation_id'];
}
if ( ( $variation_id == $product_b) ) {
wc_add_notice(__('You can\'t add this product.', 'domain'), 'error');
$passed = false; // don't add the new product to the cart
// We stop the loop
break;
}
}
return $passed;
}
In my website I use WooCommerce v3.1+ and Woocommerce Subscriptions. My products that contains items like video cameras and subscription plans. What I would like to do is:
when purchasing a camera and subscription plan, at cart page(before checkout), the quantity of the subscription plan must be equal to the quantity of cameras,
if another camera is added to the cart an error massage must appear...or something like that.
For example, if I have in my cart 2 specific products like a camera (quantity 2) and a subscription plan (quantity 1), the customer will not be able to checkout, if the subscription plan quantity does not match with cameras quantity.
I believe I have to modify the functions.php in child theme. Any help would be appreciated
Edit: I have added a piece of code in functions.php, but this will add x2 total items in cart:
add_action('woocommerce_check_cart_items', 'wh_wc_minimum_order_amount');
function wh_wc_minimum_order_amount() {
$minimum = 2;
if (WC()->cart->get_cart_contents_count() % $minimum != 0) {
// wc_clear_notices();
wc_add_notice(sprintf('<strong>Error: check product quantity</strong>', $minimum), 'error');
}
}
So this doesn't work.
Here is a complete solution that will display custom notices when normal products count doesn't match with subscription plans, warning the customer lightly. If products doesn't match your requirements, the customer will be redirected from checkout to shop page (avoiding checkout).
The code (commented):
// Replacing add to cart button link on shop and archives
add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
function replacing_add_to_cart_button( $button, $product ) {
if( $product->is_type( 'variable-subscription' ) || $product->is_type( 'variable' ) ) return $button;
$button_text = __( 'View product', 'woocommerce' );
$button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
return $button;
}
// Counting cart items (utility function)
function counting_cart_items( $subscriptions_count = 0, $products_count = 0, $wc_cart = '' ) {
$cart_obj = $wc_cart != '' ? $wc_cart : WC()->cart;
foreach( $cart_obj->get_cart() as $cart_item ){
if ( $cart_item['data']->is_type( 'subscription' ) )
$subscriptions_count += intval( $cart_item['quantity'] );
else
$products_count += intval( $cart_item['quantity'] );
}
return array( 'subscrip' => $subscriptions_count, 'product' => $products_count );
}
// Displaying Notification messages (utility function)
function conditionally_display_notice( $subscriptions_count, $products_count ) {
$count = $subscriptions_count - $products_count;
if( $subscriptions_count < $products_count )
$txt = sprintf( _n( '%s subscription plan', '%s subscriptions plans', -$count, 'woocommerce' ), -$count );
elseif( $subscriptions_count > $products_count )
$txt = sprintf( _n( '%s product', '%s products', $count, 'woocommerce' ), $count );
if( $subscriptions_count != $products_count )
wc_add_notice( sprintf( __( "You need to add %s, to be able to checkout", "woocommerce" ), $txt ), "notice" );
}
// Checking and notifying when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'conditionally_check_add_to_cart', 10, 3 );
function conditionally_check_add_to_cart( $passed, $product_id, $quantity ) {
$items_count = counting_cart_items(); // Counting cart items
$product = wc_get_product( $product_id ); // Get an instance of the WC_Product object
// Get the total live count
if( $product->is_type( 'subscription' ) )
$items_count['subscrip'] += intval( $quantity );
else
$items_count['product'] += intval( $quantity );
// Notification messages
conditionally_display_notice( $items_count['subscrip'], $items_count['product'] );
return $passed;
}
// Conditionally checking and adding your subscription when a product is added to cart
add_action( 'woocommerce_before_main_content', 'display_notice_on_shop_archives' );
function display_notice_on_shop_archives( ) {
if( is_product() ) return;
$items_count = counting_cart_items(); // Counting cart items
// Notification messages
conditionally_display_notice( $items_count['subscrip'], $items_count['product'] );
wc_print_notices();
}
/*
// Conditionally checking and adding your subscription when a product is added to cart
add_action( 'woocommerce_add_to_cart', 'conditionally_check_add_to_cart', 10, 6 );
function conditionally_check_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
$items_count = counting_cart_items(); // Counting cart items
$product = wc_get_product( $product_id ); // Get an instance of the WC_Product object
// Get the updated count
if( $product->is_type( 'subscription' ) )
$items_count['subscrip'] += intval( $quantity );
else
$items_count['product'] += intval( $quantity );
// Notification messages
conditionally_display_notice( $items_count['subscrip'], $items_count['product'] );
}
*/
// Checking and validating when updating cart item quantities
add_filter( 'woocommerce_update_cart_validation', 'conditionally_check_cart_update', 10, 4 );
function conditionally_check_cart_update( $passed, $cart_item_key, $values, $updated_quantity ) {
$items_count = counting_cart_items(); // Counting cart items
// Get the updated count
if( $values['data']->is_type( 'subscription' ) )
$items_count['subscrip'] += intval( -$values['quantity'] + $updated_quantity );
else
$items_count['product'] += intval( -$values['quantity'] + $updated_quantity );
// Notification messages
conditionally_display_notice( $items_count['subscrip'], $items_count['product'] );
return $passed;
}
// Checking and validating when updating cart item quantities
add_filter( 'woocommerce_cart_item_removed', 'conditionally_check_removed_cart_item', 10, 2 );
function conditionally_check_removed_cart_item( $cart_item_key, $wc_cart ) {
$items_count = counting_cart_items( 0, 0, $wc_cart ); // Counting cart items
// Notification messages
conditionally_display_notice( $items_count['subscrip'], $items_count['product'] );
}
// Checking and conditionally redirecting to shop page
add_action( 'template_redirect', 'conditional_checkout_redirection');
function conditional_checkout_redirection(){
if ( is_checkout() ) {
$items_count = counting_cart_items(); // Counting cart items
if ( $items_count['subscrip'] != $items_count['product']) {
// redirecting to shop page
wp_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
exit(); // always exit
}
}
}
code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested on Woocommerce 3+ and works
Certain products when have tag value "buynow" or categories by featue products added to cart I want to remove all other product in cart and dont allow to add more product in cart. When one user added one product of this type and tries to add another product in cart, It will show error notice.
I have tried this code for product id 1024
add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10, 3);
function wdm_empty_cart( $cart_item_data, $product_id, $variation_id )
{
global $woocommerce;
if($product_id == '1024'){
$woocommerce->cart->empty_cart();
wc_add_notice( 'Error!', 'error' );
}
elseif ( WC()->cart->get_cart_contents_count() >=1 ){
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = $values['data']->post;
$cartproductid[] = $_product->ID;
}
foreach($cartproductid as $id){
if($id == 1024){
wc_add_notice( 'Error!', 'error' );
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart('1024');
}
}
}
return $cart_item_data;
}
My code works as follows:
When user add 1024 product id to the cart it empty the cart and add only the 1024 product. when user add product after adding 1024 not the same product it adds one more to the cart the stops adding further product.
My requirement is when 1024 product added to the cart no other product can not add to the cart. When user try to add it shows the notice "Error!"
Any solution is appreciated. Thanks in advance.
Anyone's help appreciated.
Instead of woocommerce_add_cart_item_data you can use woocommerce_add_to_cart_validation. this works.
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_to_cart_validation_CB', 30, 3);
function woocommerce_add_to_cart_validation_CB( $bool, $product_id, $quantity )
{
global $woocommerce;
if($product_id == '1024'){
$woocommerce->cart->empty_cart();
}
elseif ( WC()->cart->get_cart_contents_count() >= 1 ){
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
if( '1024' == $values['product_id'] ){
wc_add_notice( 'Error!', 'error' );
return false;
}
}
}
return $bool;
}
If you want do this for featured product then use following code.
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_to_cart_validation_CB', 30, 3);
function woocommerce_add_to_cart_validation_CB( $bool, $product_id, $quantity )
{
global $woocommerce;
if( isFeaturedProduct($product_id)){
$woocommerce->cart->empty_cart();
}
elseif ( WC()->cart->get_cart_contents_count() >= 1 ){
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
if(isFeaturedProduct($values['product_id']) ){
wc_add_notice( 'Error!', 'error' );
return false;
}
}
}
return $bool;
}
function isFeaturedProduct( $product_id ){
$wc_product_obj = new WC_Product($product_id);
return $wc_product_obj->is_featured();
}