Hide auto added gift product from WooCommerce catalog - php

I have the following scenario that I can not solve, could you guide me, either with a plugin or from code?
I have the product A and the product B, which should not appear in the store nor can it be added individually as it is a gift.
If someone adds product A to the cart, then the system should add product B. It is like a BOGO, but the problem that I cannot solve is that of the free product that must be invisible and not allow to be purchased individually.

Based on Auto add to cart a Gift product variation programmatically in WooCommerce? answer code, here is the complete way to auto add a hidden gift product when a specific product is added to cart:
// Auto add a hidden gift product to cart based on sprcific product
add_action( 'woocommerce_before_calculate_totals', 'wc_auto_add_gift_to_cart' );
function wc_auto_add_gift_to_cart( $cart ) {
if (is_admin() && !defined('DOING_AJAX'))
return;
$required_product_id = 37; // The required product Id for a gift
$product_gift_id = 53; // The gift product Id
$has_required = $gift_key = false; // Initializing
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Check if required product is in cart
if( in_array( $required_product_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
$has_required = true;
}
// Check if gifted product is already in cart
if( in_array($product_gift_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
$gift_key = $cart_item_key;
}
}
// If gift is in cart, but not the required product: Remove gift from cart
if ( ! $has_required && $gift_key ) {
$cart->remove_cart_item( $gift_key );
}
// If gift is not in cart and the required product is in cart: Add gift to cart
elseif ( $has_required && ! $gift_key ) {
$cart->add_to_cart( $product_gift_id );
}
}
// Hide gift product from catalog (shop and archive pages)
add_action( 'woocommerce_product_query', 'hide_gift_product_from_catalog' );
function hide_gift_product_from_catalog( $q ) {
// Not in admin
if ( ! is_admin() ) {
$product_gift_id = 53;
$q->set('post__not_in', array($product_gift_id) );
}
}
// Redirect gift product single page to shop
add_action( 'template_redirect', 'redirect_gift_single_product_to_shop' );
function redirect_gift_single_product_to_shop() {
$product_gift_id = 53;
//
if ( get_the_id() == $product_gift_id ) {
wp_redirect( wc_get_page_permalink( 'shop' ) );
exit;
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Related: Auto add to cart a Gift product variation programmatically in WooCommerce?

Related

WC()->cart->add_to_cart() not working when cart page is loaded directly?

I want to add a product automatically to the cart, whenever the user goes to the cart page.
I have added the following code in cart.php:
WC()->cart->add_to_cart( $product_id );
When I try to simply visit the cart page by entering the url - example.com/cart/ , then the product above does not get added, however, when I add another product to cart on live site and click 'view cart', this particular product that I have added above via code, also gets added to the cart (I tried both, as logged in user and as guest).
I did try to set session cookie on before the above code but that didn't work either:
WC()->session->set_customer_session_cookie( true );
Try the following:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
//check if we are on cart page
if (is_cart()) {
$product_id = 69; //replace with your own product id
$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() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}

Change payment method title for specific products in WooCommerce checkout

I'm trying that, when a specific product is in the checkout, the title of the payment method changes from; for example: "Payment by card" to "Payment in parts", is it possible?
I have tried with jquery:
jQuery(function($){
if ( $('#payment-fractional-payment').length ){
$("label[for='payment_method_redsys_gw']").text("Payment in installments");
}
});
but it only changes it for a moment and returns to the default title, is there any way to do it in the functions.php with some hook?
You can use this simple hooked function, where you will have to set the correct targeted payment id and the targeted product id(s):
add_filter( 'woocommerce_gateway_title', 'change_payment_gateway_title', 100, 2 );
function change_payment_gateway_title( $title, $payment_id ){
$targeted_payment_id = 'redsys_gw'; // Set your payment method ID
$targeted_product_ids = array(37, 53); // Set your product Ids
// Only on checkout page for specific payment method Id
if( is_checkout() && ! is_wc_endpoint_url() && $payment_id === $targeted_payment_id ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $item ) {
// Check for specific products: Change payment method title
if( in_array( $item['product_id'], $targeted_product_ids ) ) {
return __("Payment in installments", "woocommerce");
}
}
}
return $title;
}
Code goes in functions.php file of the active child theme (or active theme). It should works.

WooCommerce: If specific product is the only item in cart, clear cart

If users purchase a product on my site, I give them the option of adding a discounted product to their cart at checkout. However, users are able to remove the original product from cart and the discounted product still remains within the cart.
Is it possible to have it such that if the discounted product is the only one in the cart, then the cart should be empty? I haven't found a way to do this.
What I have tried
Currently, I use the following code from bekarice found on Github:
/**
* Renders a notice and prevents checkout if the cart
* only contains products in a specific category
*/
function sv_wc_prevent_checkout_for_category() {
// set the slug of the category for which we disallow checkout
$category = 'clothing';
// get the product category
$product_cat = get_term_by( 'slug', $category, 'product_cat' );
// sanity check to prevent fatals if the term doesn't exist
if ( is_wp_error( $product_cat ) ) {
return;
}
$category_name = '' . $product_cat->name . '';
// check if this category is the only thing in the cart
if ( sv_wc_is_category_alone_in_cart( $category ) ) {
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category – you must purchase a product from another category to check out.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
/**
* Checks if a cart contains exclusively products in a given category
*
* #param string $category the slug of the product category
* #return bool - true if the cart only contains the given category
*/
function sv_wc_is_category_alone_in_cart( $category ) {
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// if a product is not in our category, bail out since we know the category is not alone
if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
return false;
}
}
// if we're here, all items in the cart are in our category
return true;
}
But I don't think it as good a method. Basically, it doesn't allow users to checkout if cart only contains items from a certain category.
You can use the following code that will check on adding to cart your specific discounted product that cart is not empty and that it's not alone in cart, removing it from cart:
// Add to cart validation for the discounted product
add_filter( 'woocommerce_add_to_cart_validation', 'check_specific_discounted_product', 10, 3 );
function check_specific_discounted_product( $passed, $product_id, $quantity ) {
// Settings
$discounted_product_id = 53;
if( WC()->cart->is_empty() && $discounted_product_id == $product_id ) {
wc_add_notice( __("This product can't be purchased alone."), 'notice' );
return false;
}
return $passed;
}
// Removing the discounted product if it's alone in cart
add_action( 'woocommerce_before_calculate_totals', 'conditionally_remove_a_discounted_product' );
function conditionally_remove_a_discounted_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$discounted_product_id = 53;
// Initializing variables
$discounted_item_key = false;
// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// When free productis is cart
if ( in_array( $discounted_product_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
$discounted_item_key = $cart_item_key;
}
// if any other product is in cart: EXIT
else {
return;
}
}
// When the discounted product is alone in cart, remove it
if( $discounted_item_key ) {
// display notice on removal (optional)
wc_clear_notices();
wc_add_notice( __("The discounted product can't be purchased alone and has been removed."), 'notice' );
$cart->remove_cart_item( $discounted_item_key ); // Remove
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Auto add product to cart except for some WooCommerce product categories

I am using Auto add a product for cart item from specific product categories in WooCommerce answer code to auto add a free product to the cart. The code works great if the product is in a specific category but I need to add the product if it is NOT in a specific category.
I am able to add the free product if it is not in the specific category with this edit:
if( **!** has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
$matched_category = true;
}
But this does not remove the free product when the parent product is removed.
Any help would be appreciated!
Updated: Here are the changes that are required to "auto add a product in cart except for specific defined product categories (not removing the auto added product if mixed categories are in cart):
add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_except_for_product_category', 10, 1 );
function auto_add_item_except_for_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Settings
$except_terms = array('t-shirts'); // Required product category(ies)
$auto_added_id = 70; // Specific product to be added automatically
$except_found = false;
$others_found = false;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Check for product category
if( has_term( $except_terms, 'product_cat', $cart_item['product_id'] ) ) {
$except_found = true;
} else {
$others_found = true;
}
// Check if specific product is already auto added
if( $cart_item['data']->get_id() == $auto_added_id ) {
$auto_added_item_key = $cart_item_key; // keep cart item key
}
}
// If auto added product is in cart with at least an item from a the defined product category only
if ( isset($auto_added_item_key) && $except_found && ! $others_found ) {
$cart->remove_cart_item( $auto_added_item_key ); // Remove specific product
}
// If there is at least an item from others product categories and the specific product is not in cart
elseif ( ! isset($auto_added_item_key) && ! $except_found ) {
$cart->add_to_cart( $auto_added_id ); // Add specific product
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Based on: Auto add a product for cart item from specific product categories in WooCommerce
Might be able to hook into the Woo's remove item from cart hook:
function remove_free_item() {
if ( is_admin() ) {
return;
}
$product_id = 'ID_OF_FREE_ITEM';
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $cart_item_key ) {
WC()->cart->remove_cart_item( $cart_item_key );
}
}
add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $cart) {
// removed item
$line_item = $cart->removed_cart_contents[ $removed_cart_item_key ];
// removed item product id
$product_id = $line_item[ 'product_id' ];
// might need to wrap this in some check depending on your case
remove_free_item();
}

Auto add a product for cart item from specific product categories in WooCommerce

I have a code to add a product (a deposit) automatically to a customers cart, no matter what product he has chosen - with the code below inside the functions.php. This works fine.
But now, how to extend the code that this product will only be automatically added to the cart when the customer has chosen a product from a specific product category? E.g. the deposit shouldn't be added to the cart when a customer buys a gift card.
Thanks a lot!
/**
* Automatically adds product to cart on visit
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 1267; //product added automatically
$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() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
}
}
}
You will have to use the Wordpress conditional function hast_term() in a completely different way.
The following code will auto add to cart a pre-defined product, if a product from a product category is already in cart:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_based_on_product_category', 10, 1 );
function auto_add_item_based_on_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$required_categories = array('t-shirts'); // Required product category(ies)
$added_product_id = 1267; // Specific product to be added automatically
$matched_category = false;
// Loop through cart items
foreach ( $cart->get_cart() as $item_key => $item ) {
// Check for product category
if( has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
$matched_category = true;
}
// Check if specific product is already auto added
if( $item['data']->get_id() == $added_product_id ) {
$saved_item_key = $item_key; // keep cart item key
}
}
// If specific product is already auto added but without items from product category
if ( isset($saved_item_key) && ! $matched_category ) {
$cart->remove_cart_item( $saved_item_key ); // Remove specific product
}
// If there is an item from defined product category and specific product is not in cart
elseif ( ! isset($saved_item_key) && $matched_category ) {
$cart->add_to_cart( $added_product_id ); // Add specific product
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Categories