Get is_purchasable hook working for Woocommerce product variations too

Asked
Active3 hr before
Viewed126 times

10 Answers

working
90%

To make product variation work you need to get the parent product ID, because your variations don't have this date range custom fields:, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,I tried to add another filter just below woocommerce_is_purchasable:,Connect and share knowledge within a single location that is structured and easy to search.

Try this revisited code for all product types (including product variations) :

add_filter('woocommerce_is_purchasable', 'purchasable_product_date_range', 20, 2);

function purchasable_product_date_range($purchasable, $product) {
   $date_from = (int) get_post_meta($product - > get_id(), '_availability_schedule_dates_from', true);
   $date_to = (int) get_post_meta($product - > get_id(), '_availability_schedule_dates_to', true);
   if (empty($date_from) || empty($date_to))
      return $purchasable; // Exit (fields are not set)

   $current_date = (int) current_time('timestamp');
   if (!($current_date >= $date_from && $current_date <= $date_to))
      $purchasable = false;

   return $purchasable;
}
load more v
88%

I have made 2 custom product fields - availability - since when/until when. So if the current date is between these set availability dates then product is purchasable, else - it's not. Everything works perfectly however only until I post a product with a variations. Then it's like product variations ignore these custom availability fields/values and still let to add variations to cart even if current date is not between set availability dates.,To make product variation work you need to get the parent product ID, because your variations don't have this date range custom fields:,But variations still ignore availability fields.,You can get all the data that you want for all product variations in a variable product this way:

I have made 2 custom product fields - availability - since when/until when. So if the current date is between these set availability dates then product is purchasable, else - it's not. Everything works perfectly however only until I post a product with a variations. Then it's like product variations ignore these custom availability fields/values and still let to add variations to cart even if current date is not between set availability dates.

function hide_product_if_unavailable($is_purchasable, $object) {

   $date_from = get_post_meta($object - > get_id(), '_availability_schedule_dates_from');
   $date_to = get_post_meta($object - > get_id(), '_availability_schedule_dates_to');
   $current_date = current_time('timestamp');

   if (strlen($date_from[0]) !== 0) {

      if (($current_date >= (int) $date_from[0]) && ($current_date <= (int) $date_to[0])) {

         return true;

      } else {

         return false;

      }

   } else {

      # Let adding product to cart
      if Availability fields was not set at all
      return true;

   }

}
add_filter('woocommerce_is_purchasable', 'hide_product_if_unavailable', 10, 2);

I tried to add another filter just below woocommerce_is_purchasable:

add_filter('woocommerce_variation_is_purchasable', 'hide_product_if_unavailable', 10, 2);
load more v
72%

I really would like an answer on this question too! The hook does work properly if you want to remove all add to chart buttons, but I only would like to remove the add to chart button on the category page and not on the single page. Is there a solution?,I want to remove the price and add to cart button functions only at a certain URL extension like http://www.mysite.com/wholesale. ,Hey! Nice article! Thanks for sharing your knowledge. I’m trying but was not able to make it work on my site. I want to remove the add to cart button if the user already bought the product.,Query : I want to hide ” add to Cart button ” for guest users all over the website and for all products.

Here’s the code for the same:

remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);

You see, these actions (which are functions), fire additional hooks. For example, the woocommerce_template_single_add_to_cart function which resides in includes/wc-template-functions.php, contains the following piece of code:

function woocommerce_template_single_add_to_cart() {
   global $product;
   do_action('woocommerce_'.$product - > product_type.
      '_add_to_cart');
}

If you look at the code single-product/add-to-cart/simple.php, you’ll notice a simple filter:

global $product;
if (!$product - > is_purchasable()) {
   return;
}

So, you just need to add the following:

add_filter('woocommerce_is_purchasable', '__return_false');
load more v
65%

runs before the init hook. The init hook is too late for some features, such, runs before the init hook. The init hook is too late for some features, such ,How I can display product variations dropdown select on the Cart page? ,function woo_display_variation_dropdown_on_shop_page() {

load more v
75%

Support » Plugin: WooCommerce » after the product is out of stock, the buttons added to the cart are hidden and,The topic ‘after the product is out of stock, the buttons added to the cart are hidden and’ is closed to new replies.,Hi @princebhalani143 I just changed the color and succeeded to change the position of the add basket button to fit other products I can not thank,@princebhalani143 thank you very much for the info This works well on a single product page what about on the shop page so that the button to add to cart changes to the text “expared”

Hi,
is there someone there who can help me?
I added this code in the theme functions.php

if (!function_exists('woocommerce_template_loop_add_to_cart')) {
   function woocommerce_template_loop_add_to_cart() {
      global $product;
      if (!$product - > is_in_stock() || !$product - > is_purchasable()) return;
      woocommerce_get_template('loop/add-to-cart.php');
   }
}
load more v
40%

Get an array of all sale and regular prices from all variations. This is used for example when displaying the price range at variable product level or seeing if the variable product is on sale.,Get an array of available variations for the current product.,Get the min or max variation regular price.,Sets an array of variation attributes.

load more v
22%

Before doing any code modifications, it’s always a good idea to take a full backup of our site and make sure that we have FTP access or access to cPanel or Plesk or other control panel with access to a file manager.,If you wonder what is the best way to add code snippets to your site, have a look at our previous article about safely adding PHP code.,We can maintain, support and manage your single, or all your clients, website with dedication,We assume that you already have WordPress with WooCommerce installed, and your store is displaying at least one product.

remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
load more v
60%

Update – 01 March 2018,You can find a link to the code for WooCommerce 3.x at the bottom of the article. ,This post was written in December 2015. Based on our tests, the code works with with WooCommerce 2.5 and 2.6. Please keep in mind that the code example are provided “as is”, without explicit or implicit warranties. You might have to adjust the code to make it work with your specific configuration.,If I understand correctly, you would like to do the following:

The first thing to do is to determine what is in the cart. The content of the cart will dictate what else can be added to it. We do this operation only once per page load, for better performance.

/**
 * Retrieves the cart contents. We can't just call WC_Cart::get_cart(), because
 * such method runs multiple actions and filters, which we don't want to trigger
 * at this stage.
 *
 * @author Aelia <support@aelia.co>
 */
function aelia_get_cart_contents() {
  $cart_contents = array();
  /**
   * Load the cart object. This defaults to the persistant cart if null.
   */
  $cart = WC()->session->get( 'cart', null );

  if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', true ) ) ) {
    $cart = $saved_cart['cart'];
  } elseif ( is_null( $cart ) ) {
    $cart = array();
  }

  if ( is_array( $cart ) ) {
    foreach ( $cart as $key => $values ) {
      $_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );

      if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
        if ( $_product->is_purchasable() ) {
          // Put session data into array. Run through filter so other plugins can load their own session data
          $session_data = array_merge( $values, array( 'data' => $_product ) );
          $cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
        }
      }
    }
  }
  return $cart_contents;
}

// Step 1 - Keep track of cart contents
add_action('wp_loaded', function() {
  // If there is no session, then we don't have a cart and we should not take
  // any action
  if(!is_object(WC()->session)) {
    return;
  }

  // This variable must be global, we will need it later. If this code were
  // packaged as a plugin, a property could be used instead
  global $allowed_cart_items;
  // We decided that products with ID 737 and 832 can go together. If any of them
  // is in the cart, all other products cannot be added to it
  global $restricted_cart_items;
  $restricted_cart_items = array(
    737,
    832,
  );

  // "Snoop" into the cart contents, without actually loading the whole cart
  foreach(aelia_get_cart_contents() as $item) {
    if(in_array($item['data']->id, $restricted_cart_items)) {
      $allowed_cart_items[] = $item['data']->id;

      // If you need to allow MULTIPLE restricted items in the cart, comment
      // the line below
      break;
    }
  }
});
load more v
48%

First, let’s start understanding why you may want to hide the Add to cart button. Removing the Add to cart button is one of the best ways of disabling the purchase process for a certain product or store. Even though it may sound counterintuitive, the truth is that deleting the Add to cart button can be very useful in some situations.,In conclusion, hiding the Add to cart button can be useful in many different situations:,There are several ways to completely hide the Add to cart button from your store. One of the easiest ones is to use the following script in the functions.php file of your child theme:,Have you had any issues with the scripts? Do you know any other ways to remove the Add to cart button? Let us know in the comments section below!

Let’s say you’re running a special offer for your registered users. You can create a special landing page and send an email with the link only to your registered customers, but what if they share it with other users? To avoid this type of situation and make sure that you only offer the discounts to the right customers, you can remove the Add to cart button from your WooCommerce store only for non-logged-in users. To do that, paste the following script in the functions.php file of your child theme:

/* REMOVE ADD TO CART BUTTON FOR NON-LOGGED-IN USERS */
if (!is_user_logged_in()) { // in product pageadd_filter('woocommerce_is_purchasable', '__return_false');
}
load more v
23%

In this post I will be using some examples of how to create a Simple Rental and Variable Rental product types. This will be packed in a small and overly simple plugin.,Thank you again for the excellent article and ‘customer service’ lol.,It would depend on the plugin’s code that is used to set the virtual attribute. Thats not something I’d be able to get to you out of the blue, it’d need to be researched in the plugin’s code first.,Hmm, seems like I indeed missed to into that deeper. I haven’t exactly done any verification on this, but I believe you should get far with just extending the existing Variable_Product class instead of the Simple_Product.

It looks like one small change is necessary to get this to work with WC 2.7+. Instead of having the product class set a property named “product_type” to your product type, it needs to implement the method “get_type()”. For example your class would become

	class WC_Product_Simple_Rental extends WC_Product_Simple {

	   public
	   function get_type() {

	      return 'simple_rental';

	   }

	}

Other "working-undefined" queries related to "Get is_purchasable hook working for Woocommerce product variations too"