WooCommerce Pre-Orders Plugin - php

I'm looking into purchasing WooCommerce Pre Orders and have been looking at a friend's copy to demo. It's a great plugin, but I have an issue I can't seem to solve.
When ordering, you can only order 1 variation of a product at a time. You can edit the quantity of that variation in the cart but you can't add 2 variations of the same product to the same cart at the same time. If you do, it will empty the cart and replace it with the current selection. Since I'd be taking pre-orders for screen printed clothing (similar to teespring), ordering multiple variations (sizes in this instance) at one time is important. Making them make multiple orders from the same product would just drive them away.
I don't want to let customers order from multiple preorders at once since each preordered product has a different release/ship date, but I want to let them order multiple variations, i.e. a Small Tee, a Medium Tee, and a Large Tee, of a particular product since they would all ship at the same time.
I hope all of that made sense.
Here is the code that is responsible for the cart restrictions. Any help is much appreciated.
/**
* When a pre-order is added to the cart, remove any other products
*
* #since 1.0
* #param bool $valid
* #param $product_id
* #return bool
*/
public function validate_cart( $valid, $product_id ) {
global $woocommerce;
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $product_id ) ) {
// if a pre-order product is being added to cart, check if the cart already contains other products and empty it if it does
if( $woocommerce->cart->get_cart_contents_count() >= 1 ) {
$woocommerce->cart->empty_cart();
$string = __( 'Your previous cart was emptied because pre-orders must be purchased separately.', 'wc-pre-orders' );
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( $string );
} else {
$woocommerce->add_message( $string );
}
}
// return what was passed in, allowing the pre-order to be added
return $valid;
} else {
// if there's a pre-order in the cart already, prevent anything else from being added
if ( $this->cart_contains_pre_order() ) {
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
} else {
$woocommerce->add_error( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
}
$valid = false;
}
}
return $valid;
}
/**
* Add any applicable pre-order fees when calculating totals
*
* #since 1.0
*/
public function maybe_add_pre_order_fee() {
global $woocommerce;
// Only add pre-order fees if the cart contains a pre-order
if ( ! $this->cart_contains_pre_order() ) {
return;
}
// Make sure the pre-order fee hasn't already been added
if ( $this->cart_contains_pre_order_fee() ) {
return;
}
$product = self::get_pre_order_product();
// Get pre-order amount
$amount = WC_Pre_Orders_Product::get_pre_order_fee( $product );
if ( 0 >= $amount ) {
return;
}
$fee = apply_filters( 'wc_pre_orders_fee', array(
'label' => __( 'Pre-Order Fee', 'wc-pre-orders' ),
'amount' => $amount,
'tax_status' => WC_Pre_Orders_Product::get_pre_order_fee_tax_status( $product ), // pre order fee inherits tax status of product
) );
// Add fee
$woocommerce->cart->add_fee( $fee['label'], $fee['amount'], $fee['tax_status'] );
}
/**
* Checks if the current cart contains a product with pre-orders enabled
*
* #since 1.0
* #return bool true if the cart contains a pre-order, false otherwise
*/
public static function cart_contains_pre_order() {
global $woocommerce;
$contains_pre_order = false;
if ( ! empty( $woocommerce->cart->cart_contents ) ) {
foreach ( $woocommerce->cart->cart_contents as $cart_item ) {
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $cart_item['product_id'] ) ) {
$contains_pre_order = true;
break;
}
}
}
return $contains_pre_order;
}
/**
* Checks if the current cart contains a pre-order fee
*
* #since 1.0
* #return bool true if the cart contains a pre-order fee, false otherwise
*/
public static function cart_contains_pre_order_fee() {
global $woocommerce;
foreach ( $woocommerce->cart->get_fees() as $fee ) {
if ( is_object( $fee ) && 'pre-order-fee' == $fee->id )
return true;
}
return false;
}
/**
* Since a cart may only contain a single pre-ordered product, this returns the pre-ordered product object or
* null if the cart does not contain a pre-order
*
* #since 1.0
* #return object|null the pre-ordered product object, or null if the cart does not contain a pre-order
*/
public static function get_pre_order_product() {
global $woocommerce;
if ( self::cart_contains_pre_order() ) {
foreach ( $woocommerce->cart->cart_contents as $cart_item ) {
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $cart_item['product_id'] ) ) {
// return the product object
return get_product( $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'] );
}
}
} else {
// cart doesn't contain pre-order
return null;
}
}

I know this post is old. But come to this same problem and i have solved my problem like this.
I have changed validate_cart() function in woocommerce-pre-orders/classes/class-wc-pre-orders-cart.php
It is like this :
public function validate_cart( $valid, $product_id ) {
global $woocommerce;
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $product_id ) ) {
if( $woocommerce->cart->get_cart_contents_count() >= 1 ) {
if ( $this->cart_contains_pre_order() ) {
return $valid;
}
$string = __( 'Your cart contains items, please complete that order first and then purchase pre-order items, because pre-orders must be purchased separately.', 'wc-pre-orders' );
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( $string );
} else {
$woocommerce->add_message( $string );
}
$valid = false;
return $valid;
}
else
{
return $valid;
}
} else {
// if there's a pre-order in the cart already, prevent anything else from being added
if ( $this->cart_contains_pre_order() ) {
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
} else {
$woocommerce->add_error( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
}
$valid = false;
}
}
return $valid;
}
Note : I know this is not the right way for implementation. Because i
have edit in plugin directly. So when plugin will update, the changes are no longer there. And you can use any 'return $valid' or 'return true' or 'return false' as your choice.
Thank you.

I've been having the same issue and just found an answer (I hope) here:
Pre-orders can only purchase one at a time
I managed to implement hortongroup's plugin fix as described in the comments.
There was a slight error the shortcode line in the description, it should read:
echo do_shortcode('[pre_order_fix]');
It now seems to be working perfectly, I'll have wait for the next update to WooCommerce Pre Orders to see if the plugin fix still works.
Ideally by doing it this way we won't have to alter WooCommerce Pre Orders after every update.
Here's the code I used for the custom plugin:
<?php
/**
* Plugin Name: Woo Pre-Order Fix
* Plugin URI:
* Description: Fix the one item only issue with Woocommerce Pre-Orders
* Version: 1.0
* Author: hortongroup
* Author URI:
* License: GPL12
*/
function pre_order_fix_shortcode() {
if ( in_array( 'woocommerce-pre-orders/woocommerce-pre-orders.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
remove_filter( 'woocommerce_add_to_cart_validation', array( $GLOBALS['wc_pre_orders']->cart, 'validate_cart' ), 15, 2 );
}
}
add_shortcode('pre_order_fix', 'pre_order_fix_shortcode');
?>
Hopefully this will work for you too:)
Kind regards,
JP

I know that it's been a long time but I think this could still be useful for someone. If you have a child theme you can just add this to functions.php:
//remove pre-order limitations --> only one item per order
add_action( 'init', 'remove_validation_cart' );
function remove_validation_cart(){
remove_filter( 'woocommerce_add_to_cart_validation', array( $GLOBALS['wc_pre_orders']->cart, 'validate_cart' ), 15, 2 );
}
This avoids the need of adding a plugin

Since this issue still exists today and my scenario was slightly different, I've used the following filter to fix my issue.
I want pre-orders to be made but not one pre-order item per order, there could be multiple quantities and different pre-order products in one order. The only scenario I want to prevent is that regular products are being mixed with pre-orders (which shouldn't be possible).
Maybe anyone else could use this approach (going to check for something custom in the future which you can add to your child-theme) which would be better since it could now be overwritten with an update.
/**
* When a pre-order is added to the cart, remove any other products
*
* #since 1.0
* #param bool $valid
* #param $product_id
* #return bool
*/
public function validate_cart( $valid, $product_id ) {
global $woocommerce;
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $product_id ) ) {
// if a pre-order product is being added to cart, check if the cart already contains other products and empty it if it does
if( $woocommerce->cart->get_cart_contents_count() >= 1 ) {
// count the amount of regular items in the cart
$regularCount = 0;
foreach ($woocommerce->cart->get_cart() as $item) {
// continue of the product is a pre-order product...
if (WC_Pre_Orders_Product::product_can_be_pre_ordered( $item['product_id'] )) {
continue;
}
$regularCount++;
}
// only clear the cart if the current items in it are having regular products...
if ($regularCount > 0) {
$woocommerce->cart->empty_cart();
$string = __( 'Your previous cart was emptied because pre-orders must be purchased separately.', 'wc-pre-orders' );
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( $string );
} else {
$woocommerce->add_message( $string );
}
}
}
// return what was passed in, allowing the pre-order to be added
return $valid;
} else {
// if there's a pre-order in the cart already, prevent anything else from being added
if ( $this->cart_contains_pre_order() ) {
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
} else {
$woocommerce->add_error( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
}
$valid = false;
}
}
return $valid;
}

Related

woocommerce order status stock reduction stop [duplicate]

I have a custom order status called 'quote', and I have added the following code to try and prevent stock levels being decremented for orders with this status.
function bw_do_not_reduce_quote_stock( $reduce_stock, $order ) {
if ( $order->has_status( 'quote' ) ) {
$reduce_stock = false;
}
return $reduce_stock;
}
add_filter( 'woocommerce_can_reduce_order_stock', 'bw_do_not_reduce_quote_stock', 10, 2 );
This works for orders placed on the front-end website. But if the admin adds or edits an order on the backend, the stock is decremented.
Is there an alternative hook for the backend? Or am I missing something else?
In addition to your current code, add the woocommerce_prevent_adjust_line_item_product_stock filter hook
/**
* Prevent adjust line item
*
* #param $prevent
* #param $item
* #param $quantity
*/
function filter_woocommerce_prevent_adjust_line_item_product_stock ( $prevent, $item, $quantity ) {
// Get order
$order = $item->get_order();
if ( $order->has_status( 'quote' ) ) {
$prevent = true;
}
return $prevent;
}
add_filter( 'woocommerce_prevent_adjust_line_item_product_stock', 'filter_woocommerce_prevent_adjust_line_item_product_stock', 10, 3 );

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.

Hide WooCommerce product if already purchased by logged in user

I am creating an LMS using LearnDash + WooCommerce. So far so good. Now, I'd like to hide a Product when the logged-in user has already purchased it to a) prevent the user from purchasing it twice, and b) so that I can display a product grid for them without the already purchased item(s).
Another example: if a user who purchased ITEM A goes to the shop, ITEM A should not even be displayed for them.
Thanks so much!
So, I ended up with a nice workaround:
On the product page, I created a CUSTOM FIELD where I can input the COURSE ID.
Then, with PHP, I check the Product and retrieve the custom field for the COURSE ID.
LearnDash has a shortcode for students... so after retrieving the course ID, I can display a message/button for users who have registered already for this course.
This is the code:
<?php
global $product;
$postid = $product->get_id();
$courseid = get_post_meta( $product->get_id(), 'ID_del_curso', true );
$html = '"]<center><div class="alreadyPurchased"><i class="fas fa-graduation-cap paddingRightM"></i> Ya te has registrado</div></center>';
$openIT = '[student course_id="';
$closeIT = '[/student]';
echo do_shortcode( $openIT . $courseid . $html . $closeIT );
?>
Hope it helps!
There is a simpler solution.
Use this LearnDash shortcode...
[visitor]
Hello visitor.
Put your "Buy now" button here.
[/visitor]
/**
* Disables repeat purchase for products / variations
*
* #param bool $purchasable true if product can be purchased
* #param \WC_Product $product the WooCommerce product
* #return bool $purchasable the updated is_purchasable check
*/
function sv_disable_repeat_purchase( $purchasable, $product ) {
// Don't run on parents of variations,
// function will already check variations separately
if ( $product->is_type( 'variable' ) ) {
return $purchasable;
}
// Get the ID for the current product (passed in)
$product_id = $product->get_id();
// return false if the customer has bought the product / variation
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $product_id ) ) {
$purchasable = false;
}
return $purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'sv_disable_repeat_purchase', 10, 2 );
/**
* Shows a "purchase disabled" message to the customer
*/
function sv_purchase_disabled_message() {
global $product; // get the current product to see if it has been purchased
if ( $product->is_type( 'variable' ) ) {
foreach ( $product->get_children() as $variation_id ) {
// Render the purchase restricted message if it has been purchased
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $variation_id ) ) {
sv_render_variation_non_purchasable_message( $product, $variation_id );
}
}
} else {
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $product->get_id() ) ) {
echo '<div class="woocommerce"><div class="woocommerce-info wc-nonpurchasable-message">You\'ve already purchased this product! It can only be purchased once.</div></div>';
}
}
}
add_action( 'woocommerce_single_product_summary', 'sv_purchase_disabled_message', 31 );
/**
* Generates a "purchase disabled" message to the customer for specific variations
*
* #param \WC_Product $product the WooCommerce product
* #param int $no_repeats_id the id of the non-purchasable product
*/
function sv_render_variation_non_purchasable_message( $product, $no_repeats_id ) {
// Double-check we're looking at a variable product
if ( $product->is_type( 'variable' ) && $product->has_child() ) {
$variation_purchasable = true;
foreach ( $product->get_available_variations() as $variation ) {
// only show this message for non-purchasable variations matching our ID
if ( $no_repeats_id === $variation['variation_id'] ) {
$variation_purchasable = false;
echo '<div class="woocommerce"><div class="woocommerce-info wc-nonpurchasable-message js-variation-' . sanitize_html_class( $variation['variation_id'] ) . '">You\'ve already purchased this product! It can only be purchased once.</div></div>';
}
}
}
if ( ! $variation_purchasable ) {
wc_enqueue_js("
jQuery('.variations_form')
.on( 'woocommerce_variation_select_change', function( event ) {
jQuery('.wc-nonpurchasable-message').hide();
})
.on( 'found_variation', function( event, variation ) {
jQuery('.wc-nonpurchasable-message').hide();
if ( ! variation.is_purchasable ) {
jQuery( '.wc-nonpurchasable-message.js-variation-' + variation.variation_id ).show();
}
})
.find( '.variations select' ).change();
");
}
}
Gist snippet got from here - please check

How to display message wc_print_notice on a custom page

I have a snippet I got from https://businessbloomer.com/woocommerce-check-product-category-cart/ which is:
/*
* #snippet Check if Product Category is in the Cart - WooCommerce
* #how-to Watch tutorial # https://businessbloomer.com/?p=19055
* #sourcecode https://businessbloomer.com/?p=72900
* #author Rodolfo Melogli
* #testedwith WooCommerce 3.1.2
*/
add_action('woocommerce_before_cart', 'bbloomer_check_category_in_cart');
function bbloomer_check_category_in_cart() {
// Set $cat_in_cart to false
$cat_in_cart = false;
// Loop through all products in the Cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// If Cart has category "download", set $cat_in_cart to true
if ( has_term( 'download', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
// Do something if category "download" is in the Cart
if ( $cat_in_cart ) {
// For example, print a notice
wc_print_notice( 'Category Downloads is in the Cart!', 'notice' );
// Or maybe run your own function...
// ..........
}
}
It displays a notice if a product category is in the cart but it display the message via wc_print_notice on the cart page. I would like to display this message on a custom theme page template either via a short-code or any suggestions are welcome.
How about:
// modify the function above
if ( $cat_in_cart )
{
$msg = 'Category Downloads is in the Cart!';
wc_print_notice( $msg, 'notice' );
return $msg;
}
return null;
...
// create a new function for the shortcode
// it can be after the above function
add_shortcode( 'myshortcode', 'myshortcode_func' );
function myshortcode_func( $atts ) {
return (($msg = bbloomer_check_category_in_cart()) !== null)
? '<div class="msg">' . esc_html ($msg) . '</div>'
: ''
;
}
Then just add the shortcode in the page content.
[myshortcode]

Exclude variations with 2 specific attribute terms from coupon usage in Woocommerce

I need to prevent coupons being used if customer have any specific product variations in their cart with following attribute terms:
attribute_pa_style => swirly
attribute_pa_style => circle
I've looked through the Woocommerce scripts that apply to restricting specific products and specific categories, but can't figure it out with regard to attributes and all coupons.
Any help is appreciated.
This can be done using woocommerce_coupon_is_valid filter hook this way:
add_filter( 'woocommerce_coupon_is_valid', 'check_if_coupons_are_valid', 10, 3 );
function check_if_coupons_are_valid( $is_valid, $coupon, $discount ){
// YOUR ATTRIBUTE SETTINGS BELOW:
$taxonomy = 'pa_style';
$term_slugs = array('swirly', 'circle');
// Loop through cart items and check for backordered items
foreach ( WC()->cart->get_cart() as $cart_item ) {
foreach( $cart_item['variation'] as $attribute => $term_slug ) {
if( $attribute === 'attribute_'.$taxonomy && in_array( $term_slug, $term_slugs ) ) {
$is_valid = false; // attribute found, coupons are not valid
break; // Stop and exit from the loop
}
}
}
return $is_valid;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
You could also check each product in the cart and restrict it from the coupon with woocommerce_coupon_is_valid_for_product
/**
* exclude a product from an coupon by attribute value
*/
add_filter('woocommerce_coupon_is_valid_for_product', 'exclude_product_from_coupon_by_attribute', 12, 4);
function exclude_product_from_coupon_by_attribute($valid, $product, $coupon, $values ){
/**
* attribute Settings
*/
$taxonomy = 'pa_saison';
$term_slugs = array('SS22');
/**
* check if the product has the attribute and value
* and if yes restrict this product from the coupon
*/
if(in_array($product->get_attribute($taxonomy), $term_slugs)) {
$valid = false;
/**
* otherwise check if its a variation product
*/
} elseif($product->parent_id) {
/**
* set the parent product
*/
$parent = wc_get_product($product->parent_id);
/**
* check if parent has an attribute with this value
*/
if(in_array($parent->get_attribute($taxonomy), $term_slugs)) {
$valid = false;
}
/**
* for all other products which does not have the attribute with the value
* set the coupon to valid
*/
} else {
$valid = true;
}
return $valid;
}
I have tested it on my site and it works as expected.

Categories