How one can use Woocommerce coupons in 23 other ways? (23 easy hacks)

On this submit I’ll present you learn how to use Woocommerce coupons in 23 other ways. Which means I’m going to make use of 23 completely different hacks to make it work like attraction.

Now, as a way to make this work, add your chosen snippets proven to your baby theme’s features.php file or higher but, use a snippet supervisor like Code Snippets or WpCodeBox (my favourite). In the event you’re , then seize WPCodeBox with a pleasant 20% low cost right here (SAVE 20% Coupon WPSH20).

Video: How one can use Woocommerce coupons in 23 other ways?

How one can Filter Woocommerce orders by coupons used?

If you want to know learn how to filter Woocommerce orders by coupons used, then it’s only a snippet away. That’s, use this one right here under.

<span position="button" tabindex="0" data-code="// Filter Woocommerce orders by coupons used
outlined( 'ABSPATH' ) or exit;

// fireplace it up!
add_action( 'plugins_loaded', 'wc_filter_orders_by_coupon' );

class WC_Filter_Orders_By_Coupon {
const VERSION = '1.1.0';

/** @var WC_Filter_Orders_By_Coupon single occasion of this plugin */
protected static $occasion;
public perform __construct() {

// load translations
add_action( 'init', array( $this, 'load_translation' ) );
if ( is_admin() && ! outlined( 'DOING_AJAX' ) ) {

// provides the coupon filtering dropdown to the orders web page
add_action( 'restrict_manage_posts', array( $this, 'filter_orders_by_coupon_used' ) );

// makes coupons filterable
add_filter( 'posts_join', array( $this, 'add_order_items_join' ) );
add_filter( 'posts_where', array( $this, 'add_filterable_where' ) );
}
}

public perform filter_orders_by_coupon_used() {
international $typenow;

if ( 'shop_order' === $typenow ) {

$args = array(
'posts_per_page' => – 1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
);

$coupons = get_posts( $args );

if ( ! empty( $coupons ) ) : ?>

<choose title="_coupons_used" id="dropdown_coupons_used">
<choice worth="">
<?php esc_html_e( 'Filter by coupon used', 'wc-filter-orders' ); ?>
</choice>
<?php foreach ( $coupons as $coupon ) : ?>
<choice worth="<?php echo esc_attr( $coupon->post_title ); ?>" <?php echo esc_attr( isset( $_GET['_coupons_used'] ) ? chosen( $coupon->post_title, $_GET['_coupons_used'], false ) : '' ); ?>>
<?php echo esc_html( $coupon->post_title ); ?>
</choice>
<?php endforeach; ?>
</choose>

// Filter Woocommerce orders by coupons used
outlined( 'ABSPATH' ) or exit;

// fireplace it up!
add_action( 'plugins_loaded', 'wc_filter_orders_by_coupon' );

 class WC_Filter_Orders_By_Coupon {
	const VERSION = '1.1.0';

	/** @var WC_Filter_Orders_By_Coupon single occasion of this plugin */
	protected static $occasion;
	public perform __construct() {

		// load translations
		add_action( 'init', array( $this, 'load_translation' ) );
		if ( is_admin() && ! outlined( 'DOING_AJAX' ) ) {

			// provides the coupon filtering dropdown to the orders web page
			add_action( 'restrict_manage_posts', array( $this, 'filter_orders_by_coupon_used' ) );

			// makes coupons filterable
			add_filter( 'posts_join',  array( $this, 'add_order_items_join' ) );
			add_filter( 'posts_where', array( $this, 'add_filterable_where' ) );
		}
	}

	public perform filter_orders_by_coupon_used() {
		international $typenow;

		if ( 'shop_order' === $typenow ) {

			$args = array(
				'posts_per_page' => - 1,
				'orderby'        => 'title',
				'order'          => 'asc',
				'post_type'      => 'shop_coupon',
				'post_status'    => 'publish',
			);

			$coupons = get_posts( $args );

			if ( ! empty( $coupons ) ) : ?>

				<choose title="_coupons_used" id="dropdown_coupons_used">
					<choice worth="">
						<?php esc_html_e( 'Filter by coupon used', 'wc-filter-orders' ); ?>
					</choice>
					<?php foreach ( $coupons as $coupon ) : ?>
						<choice worth="<?php echo esc_attr( $coupon->post_title ); ?>" <?php echo esc_attr( isset( $_GET['_coupons_used'] ) ? chosen( $coupon->post_title, $_GET['_coupons_used'], false ) : '' ); ?>>
							<?php echo esc_html( $coupon->post_title ); ?>
						</choice>
					<?php endforeach; ?>
				</choose>
			<?php endif;
		}
	}

	public perform add_order_items_join( $be part of ) {
		international $typenow, $wpdb;

		if ( 'shop_order' === $typenow && isset( $_GET['_coupons_used'] ) && ! empty( $_GET['_coupons_used'] ) ) {

			$be part of .= "LEFT JOIN {$wpdb->prefix}woocommerce_order_items woi ON {$wpdb->posts}.ID = woi.order_id";
		}

		return $be part of;
	}

	public perform add_filterable_where( $the place ) {
		international $typenow, $wpdb;

		if ( 'shop_order' === $typenow && isset( $_GET['_coupons_used'] ) && ! empty( $_GET['_coupons_used'] ) ) {

			// Major WHERE question half
			$the place .= $wpdb->put together( " AND woi.order_item_type='coupon' AND woi.order_item_name='%s'", wc_clean( $_GET['_coupons_used'] ) );
		}

		return $the place;
	}

	public perform load_translation() {
		// localization
		load_plugin_textdomain( 'wc-filter-orders', false, dirname( plugin_basename( __FILE__ ) ) . '/i18n/languages' );
	}

	public static perform occasion() {
		if ( is_null( self::$occasion ) ) {
		 	self::$occasion = new self();
		}
		return self::$occasion;
	}

	public perform __clone() {
		/* translators: Placeholders: %s - plugin title */
		_doing_it_wrong( __FUNCTION__, sprintf( esc_html__( 'You can't clone situations of %s.', 'wc-filter-orders' ), 'Filter WC Orders by Coupon' ), '1.1.0' );
	}

	public perform __wakeup() {
		/* translators: Placeholders: %s - plugin title */
		_doing_it_wrong( __FUNCTION__, sprintf( esc_html__( 'You can't unserialize situations of %s.', 'wc-filter-orders' ), 'Filter WC Orders by Coupon' ), '1.1.0' );
	}
}

perform wc_filter_orders_by_coupon() {
	return WC_Filter_Orders_By_Coupon::occasion();
}

How one can show used coupons on WooCommerce admin orders record?

If you want to show used coupons on WooCommerce admin orders record then use this snippet right here under. If no coupons are used then “No coupons used” is displayed. See the screenshot above.

<span position="button" tabindex="0" data-code="// Show used coupons on WooCommerce admin orders record
add_filter( 'manage_edit-shop_order_columns', 'woo_customer_order_coupon_column_for_orders' );
perform woo_customer_order_coupon_column_for_orders( $columns ) {
$new_columns = array();

foreach ( $columns as $column_key => $column_label ) {
if ( 'order_total' === $column_key ) {
$new_columns['order_coupons'] = __('Coupons', 'woocommerce');
}

$new_columns[$column_key] = $column_label;
}
return $new_columns;
}

add_action( 'manage_shop_order_posts_custom_column' , 'woo_display_customer_order_coupon_in_column_for_orders' );
perform woo_display_customer_order_coupon_in_column_for_orders( $column ) {
international $the_order, $submit;
if( $column == 'order_coupons' ) {
if( $coupons = $the_order->get_coupon_codes() ) {
echo implode(', ', $coupons) . ' ('.depend($coupons).')';
} else {
echo '<small><em>'. __('No coupon used') . '</em>

// Show used coupons on WooCommerce admin orders record
add_filter( 'manage_edit-shop_order_columns', 'woo_customer_order_coupon_column_for_orders' );
perform woo_customer_order_coupon_column_for_orders( $columns ) {
    $new_columns = array();

    foreach ( $columns as $column_key => $column_label ) {
        if ( 'order_total' === $column_key ) {
            $new_columns['order_coupons'] = __('Coupons', 'woocommerce');
        }

        $new_columns[$column_key] = $column_label;
    }
    return $new_columns;
}

add_action( 'manage_shop_order_posts_custom_column' , 'woo_display_customer_order_coupon_in_column_for_orders' );
perform woo_display_customer_order_coupon_in_column_for_orders( $column ) {
    international $the_order, $submit;
    if( $column  == 'order_coupons' ) {
        if( $coupons = $the_order->get_coupon_codes() ) {
            echo implode(', ', $coupons) . ' ('.depend($coupons).')';
        } else {
            echo '<small><em>'. __('No coupon used') . '</em></small>';
        }
    }
}

How one can show used coupons on Woocommerce order preview template?

With the earlier snippet we’re displaying coupons within the Woocommerce admin orders record. Now, with the assistance of this one right here we’re going to show used coupons on Woocommerce order preview template.

<span position="button" tabindex="0" data-code="// Show used coupons on Woocommerce order preview template

add_filter( 'woocommerce_admin_order_preview_get_order_details', 'wpsh_coupon_in_order_preview', 10, 2 );
perform wpsh_coupon_in_order_preview( $knowledge, $order ) {
// Change '_custom_meta_key' by the right postmeta key
if( $coupons = $order->get_used_coupons() ) {
$knowledge['coupons_count'] = depend($coupons); // <= Retailer the depend within the knowledge array.
$knowledge['coupons_codes'] = implode(', ', $coupons); // <= Retailer the depend within the knowledge array.
}
return $knowledge;
}
// Show coupon in Order preview
add_action( 'woocommerce_admin_order_preview_end', 'wpsh_coupon_in_order_preview_data' );
perform wpsh_coupon_in_order_preview_data(){
// Name the saved worth and show it
echo '<div><robust>' . __('Coupons used') . ' ({{knowledge.coupons_count}})<robust>: {{knowledge.coupons_codes}}</div>

// Show used coupons on Woocommerce order preview template

add_filter( 'woocommerce_admin_order_preview_get_order_details', 'wpsh_coupon_in_order_preview', 10, 2 );
perform wpsh_coupon_in_order_preview( $knowledge, $order ) {
    // Change '_custom_meta_key' by the right postmeta key
    if( $coupons = $order->get_used_coupons() ) {
        $knowledge['coupons_count'] = depend($coupons); // <= Retailer the depend within the knowledge array.
        $knowledge['coupons_codes'] = implode(', ', $coupons); // <= Retailer the depend within the knowledge array.
    }
    return $knowledge;
}
// Show coupon in Order preview
add_action( 'woocommerce_admin_order_preview_end', 'wpsh_coupon_in_order_preview_data' );
perform wpsh_coupon_in_order_preview_data(){
    // Name the saved worth and show it
    echo '<div><robust>' . __('Coupons used') . ' ({{knowledge.coupons_count}})<robust>: {{knowledge.coupons_codes}}</div><br>';
}

How one can take away Woocommerce cost gateways if any coupon code is utilized?

Let’s think about that you just want to take away Woocommerce cost gateway in case your buyer has used a coupon. Effectively, there you go – on this instance right here under we’ll take away BACS and Paypal cost gateways if any coupon is used.

// Take away Woocommerce cost gateways if any coupon code is utilized
add_filter('woocommerce_available_payment_gateways', 'wpsh_remove_payment_for_used_coupons');

perform wpsh_remove_payment_for_used_coupons($available_gateways)
{
    $coupons = WC()->cart->applied_coupons;
    if (!empty($coupons)) {
        unset($available_gateways['bacs']); // Take away Direct financial institution switch
	  unset($available_gateways['paypal']); // Take away Paypal
    }
    return $available_gateways;
}

How one can take away Woocommerce cost gateways if a selected coupon code is utilized?

However what occurs if you need to take away Woocommerce cost gateways if a selected coupon is used? On this case, simply use this snippet right here under. This may take away BACS and Paypal gateways onlu if coupon ABC30 is used.

// Take away Woocommerce cost gateways if a selected coupon code is utilized 
add_filter('woocommerce_available_payment_gateways', 'wpsh_remove_payment_for_specific_coupon');

perform wpsh_remove_payment_for_specific_coupon($available_gateways)
{

    $coupons = WC()->cart->applied_coupons;

    foreach ($coupons as $coupon) {

        if ($coupon == 'abc30') { // Add the coupon code right here
           unset($available_gateways['bacs']); // Take away Direct financial institution switch
		   unset($available_gateways['paypal']); // Take away Paypal
        }
    }
    return $available_gateways;
}

How one can auto-apply coupon at Woocommerce Checkout Web page utilizing URL?

In the present day I provides you with two choices on learn how to auto-apply a coupon at Woocommerce checkout web page. The primary snippet right here under means that you can add a coupon utilizing url.

Step 1: add the code snippet

// Auto-apply coupon at Woocommerce Checkout Web page utilizing URL
perform enable_woocommerce_coupon_links(){
	if (!function_exists('WC') || !WC()->session) {
		return;
	}
	$query_var = apply_filters('woocommerce_coupon_links_query_var', 'coupon_code');

	// Bail if a coupon code isn't within the question string.
	if (empty($_GET[$query_var])) {
		return;
	}

	// Set a session cookie to persist the coupon in case the cart is empty.
	WC()->session->set_customer_session_cookie(true);

	// Apply the coupon to the cart if mandatory.
	if (!WC()->cart->has_discount($_GET[$query_var])) {

		// WC_Cart::add_discount() sanitizes the coupon code.
		WC()->cart->add_discount($_GET[$query_var]);
	}
}
add_action('wp_loaded', 'enable_woocommerce_coupon_links', 30);
add_action('woocommerce_add_to_cart', 'enable_woocommerce_coupon_links');

Step 2: Use URL that comprises your coupon code

For instance, if in case you have a coupon test20 and you utilize URL https://yoursite.com/checkout/?coupon_code=test20 then your coupon is robotically utilized. Don’t neglect to alter your coupon code accordingly.

How one can auto-apply coupon at Woocommerce Checkout Web page utilizing button?

You too can add a button that auto-.applies coupon code to your Woocommerce checkout web page.

This snippet right here under provides the heading “Would you like 20% low cost?” together with the button to your assessment order type. If the person clicks on the button then this Woocommerce coupon is auto-applied. See the screenshot.

How to auto-apply coupon at Woocommerce Checkout Page using URL?
<span position="button" tabindex="0" data-code="// Auto-apply coupon at Woocommerce Checkout Web page utilizing button

add_action( 'woocommerce_review_order_before_payment', 'coupon_button', 10 );
perform coupon_button() {
echo '<h4>Would you like 20% low cost?</h4>';
echo '<p><a category="button" href="?coupon_code=test20"> Click on so as to add your low cost </a>

// Auto-apply coupon at Woocommerce Checkout Web page utilizing button

add_action( 'woocommerce_review_order_before_payment', 'coupon_button', 10 );
perform coupon_button() {
      echo '<h4>Would you like 20% low cost?</h4>';
      echo '<p><a category="button" href="?coupon_code=test20"> Click on so as to add your low cost </a></p>'; // Change the coupon code accordingly
}

How one can take away Woocommerce “Have a coupon?” part from checkout web page?

On this half I’m going to indicate you learn how to customise Woocommerce checkout web page by eradicating “Have a coupon” part.

First choice, go to Woocommerce >> Settings and uncheck “Allow using coupon codes” choice. This may disable coupon codes site-wide.

Second choice, If you want to make use of coupon codes and simply need to take away Woocommerce “Have a coupon?” part from checkout web page then use this small snippet right here.

remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );

How one can auto-expand coupon area on Woocommerce checkout web page? No have to click on on the “Have a coupon?” hyperlink.

Let’s be sincere: it’s a bit annoying to click on on a “Have a coupon?” hyperlink in your Woocommerce checkout web page. Subsequently, let’s auto-expand the coupon area and take away another pointless click on.

<span position="button" tabindex="0" data-code="// Auto-expand coupon area on Woocommerce checkout web page
add_filter( 'woocommerce_checkout_coupon_message', 'wpsh_autoexpand_coupon_field', 20, 1 );
perform wpsh_autoexpand_coupon_field( $message ) {
?>
<script kind='textual content/javascript'>
jQuery(doc).prepared( perform($){
setTimeout(perform(){
$('type.checkout_coupon').css('show','block');
}, 300);
});
</script>
<?php
// HERE your customized message
return __( 'Have a coupon? Add it to the sector right here under', 'woocommerce' ) . ' <a category="showcoupon-off">' . __( '', 'woocommerce' ) . '

// Auto-expand coupon area on Woocommerce checkout web page
add_filter( 'woocommerce_checkout_coupon_message', 'wpsh_autoexpand_coupon_field', 20, 1 );
perform wpsh_autoexpand_coupon_field( $message ) {
    ?>
        <script kind='textual content/javascript'>
            jQuery(doc).prepared( perform($){
                setTimeout(perform(){
                    $('type.checkout_coupon').css('show','block');
                }, 300);
            });
        </script>
    <?php
    // HERE your customized message
    return __( 'Have a coupon? Add it to the sector right here under', 'woocommerce' ) . ' <a category="showcoupon-off">' . __( '', 'woocommerce' ) . '</a>';
}

How one can change Woocommerce coupon area location on cart web page?

With the assistance of this snippet right here you may transfer your Woocommerce area location in cart web page. See the screenshot.

How to Woocommerce coupon field location in cart page?

Listen that you’d additionally want to make use of some CSS for it. This may take away your unique coupon area and tweak your coupon and cart buttons a bit.

<span position="button" tabindex="0" data-code="// Change Woocommerce coupon area location on cart web page
add_action( 'woocommerce_proceed_to_checkout', 'move_cart_coupon_field', 1 );
perform move_cart_coupon_field() {
?>
<type class="woocommerce-coupon-form" motion="<?php echo esc_url( wc_get_cart_url() ); ?>" technique="submit">
<?php if ( wc_coupons_enabled() ) { ?>
<div class="coupon under-proceed">
<enter kind="textual content" title="coupon_code" class="input-text" id="coupon_code" worth="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" fashion="width: 100%" />
<button kind="submit" class="button" title="apply_coupon" worth="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>" fashion="width: 100%"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>
</div>
<?php } ?>
</type>

// Change Woocommerce coupon area location on cart web page
add_action( 'woocommerce_proceed_to_checkout', 'move_cart_coupon_field', 1 );
perform move_cart_coupon_field() {
   ?> 
      <type class="woocommerce-coupon-form" motion="<?php echo esc_url( wc_get_cart_url() ); ?>" technique="submit">
         <?php if ( wc_coupons_enabled() ) { ?>
            <div class="coupon under-proceed">
               <enter kind="textual content" title="coupon_code" class="input-text" id="coupon_code" worth="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" fashion="width: 100%" /> 
               <button kind="submit" class="button" title="apply_coupon" worth="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>" fashion="width: 100%"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>
            </div>
         <?php } ?>
      </type>
   <?php
}

Add this piece of CSS code to your Customizer >> Extra CSS space.

.coupon.under-proceed {
	margin-bottom: 0.5em;
}
.coupon.under-proceed button {
	margin-top: 0.5em;
	background: #2a2a2a;
}
/* Cover unique Coupon type */
div.coupon:not(.under-proceed) { 
show: none !necessary; 
}
  @media solely display screen and (max-width: 1024px) {
.woocommerce-cart-form__contents .actions .button {
    show: none;
}
}

How one can change Woocommerce coupon area location on checkout web page v.1?

In the event you just like the styling and format of the earlier hack and also you want to show it additionally on a Woocommerce checkout web page (underneath the Place order button), then use this snippet right here under (and don’t neglect so as to add CSS from the earlier snippet).

<span position="button" tabindex="0" data-code="// Transfer Woocommerce coupon area location in checkout web page
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
add_action( 'woocommerce_review_order_after_submit', 'move_checkout_coupon_field', 1 );

perform move_checkout_coupon_field() {
?>
<type class="woocommerce-coupon-form" motion="<?php echo esc_url( wc_get_checkout_url() ); ?>" technique="submit">
<?php if ( wc_coupons_enabled() ) { ?>
<div class="coupon under-proceed">
<enter kind="textual content" title="coupon_code" class="input-text" id="coupon_code" worth="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" fashion="width: 100%; margin-top: 10px;" />
<button kind="submit" class="button" title="apply_coupon" worth="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>" fashion="width: 100%"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>
</div>
<?php } ?>
</type>

// Transfer Woocommerce coupon area location in checkout web page
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
add_action( 'woocommerce_review_order_after_submit', 'move_checkout_coupon_field', 1 );

perform move_checkout_coupon_field() {
   ?> 
      <type class="woocommerce-coupon-form" motion="<?php echo esc_url( wc_get_checkout_url() ); ?>" technique="submit">
         <?php if ( wc_coupons_enabled() ) { ?>
            <div class="coupon under-proceed">
               <enter kind="textual content" title="coupon_code" class="input-text" id="coupon_code" worth="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" fashion="width: 100%; margin-top: 10px;" /> 
               <button kind="submit" class="button" title="apply_coupon" worth="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>" fashion="width: 100%"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>
            </div>
         <?php } ?>
      </type>
   <?php
}

How one can change Woocommerce coupon area location on checkout web page v.2?

There’s additionally one other technique to transfer your Woocommerce coupon area location on checkout web page. Right here’s the top consequence.

How to change Woocommerce coupon field location on checkout page?

So, to make it work like that, simply use this snippet.

// Change Woocommerce coupon area location in checkout web page?
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
add_action( 'woocommerce_review_order_after_submit', 'wpsh_move_coupon_button', 1 );
 
perform wpsh_move_coupon_button() {
  echo '<hr/';
   woocommerce_checkout_coupon_form();
}

How one can make including a coupon obligatory for sure Woocommerce merchandise?

This snippet right here under means that you can make including a coupon obligatory for sure Woocommerce merchandise. For instance, see the screenshot right here under.

Make adding a coupon is mandatory for certain Woocommerce products

What occurs right here is that:

  • If cart comprises a product with ID-s 400 (Golden lamp) or 510 (Hartek lamp)
  • then including a coupon “abs30” or “test20” is obligatory
  • in any other case the checkout web page is disabled
  • if coupon is added then checkout web page is open

// Make including a coupon obligatory for sure Woocommerce merchandise
add_action( 'woocommerce_check_cart_items', 'wpsh_mandatory_coupon' );
perform wpsh_mandatory_coupon() {
    $targeted_ids  = array(400, 510); // Add the product ID-s for the obligatory coupon right here
    $coupon_codes  = array('abc30', 'test20'); // Add the coupon codes right here

    $coupons_found = array_intersect( array_filter( array_map( 'sanitize_title', $coupon_codes) ), WC()->cart->get_applied_coupons() );

    // Loop by way of cart objects
    foreach(WC()->cart->get_cart() as $merchandise ) {
        // Verify cart merchandise for outlined product Ids and utilized coupon
        if( in_array( $merchandise['product_id'], $targeted_ids ) && empty($coupons_found) ) {
            wc_clear_notices(); // Clear all different notices

            // Keep away from checkout displaying an error discover
            wc_add_notice( sprintf( 'The product "%s" requires a coupon for checkout.', $merchandise['data']->get_name() ), 'error' );
            break; // cease the loop
        }
    }
}

How one can not apply any coupon if WooCommerce Cart comprises back-ordered merchandise?

One among my clients requested not too long ago learn how to not apply any coupon if WooCommerce Cart comprises back-ordered merchandise? If in case you have the identical query, then simply use this snippet right here under.

<span position="button" tabindex="0" data-code="// Don’t apply any coupon if WooCommerce Cart comprises back-ordered merchandise?
add_filter( 'woocommerce_coupon_is_valid', 'wpsh_disable_coupons_for_backorder', 99, 2 );
perform wpsh_disable_coupons_for_backorder( $legitimate, $coupon ){

$legitimate = true;

foreach ( WC()->cart->get_cart() as $cart_item ) {
// if($values['data']->backorders_allowed()){ //examine if backorders are allowed on this product
// get the inventory amount – returns the accessible quantity quantity
$stock_info = $cart_item['data']->get_stock_quantity();

if( $stock_info

// Don’t apply any coupon if WooCommerce Cart comprises back-ordered merchandise?
add_filter( 'woocommerce_coupon_is_valid', 'wpsh_disable_coupons_for_backorder', 99, 2 );
perform wpsh_disable_coupons_for_backorder( $legitimate, $coupon ){

    $legitimate = true;

    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // if($values['data']->backorders_allowed()){ //examine if backorders are allowed on this product
        // get the inventory amount - returns the accessible quantity quantity
        $stock_info = $cart_item['data']->get_stock_quantity();

        if( $stock_info < 1 ){
            $legitimate = false; 
            break;
        }
    }
    return $legitimate ;
}

How one can show Woocommerce coupon low cost share on cart and checkout web page?

By default, Woocommerce doesn’t show a reduction share and as a substitute reveals solely that coupon has been utilized. So, if you need to show Woocommerce coupon low cost share in cart and checkout web page then use this snippet.

Right here’s the consequence.

Display Woocommerce coupon discount percentage on cart and checkout page
<span position="button" tabindex="0" data-code="// Show Woocommerce Coupon low cost share in cart and checkout web page
add_filter('woocommerce_cart_totals_coupon_html','wpsh_coupon_percentage',10,2);
add_filter('woocommerce_checkout_item_subtotal','wpsh_coupon_percentage',10,2);
perform wpsh_coupon_percentage($worth, $coupon)
{
if($coupon->get_discount_type() == '%' && !empty($coupon->get_amount()))
{
$amt = "<p><em><robust>You’ve acquired a take care of {$coupon->get_amount()}% OFF</robust></em>

// Show Woocommerce Coupon low cost share in cart and checkout web page
add_filter('woocommerce_cart_totals_coupon_html','wpsh_coupon_percentage',10,2);
add_filter('woocommerce_checkout_item_subtotal','wpsh_coupon_percentage',10,2);
perform wpsh_coupon_percentage($worth, $coupon)
{
    if($coupon->get_discount_type() == '%' && !empty($coupon->get_amount()))
    {
        $amt = "<p><em><robust>You’ve acquired a take care of {$coupon->get_amount()}% OFF</robust></em></p>";   
    }

    return $worth.$amt;
}

How one can show Woocommerce product low cost in cart and checkout web page after coupon is utilized?

Now let’s check out learn how to show Woocommerce product low cost in cart and checkout web page after coupon is utilized. See screenshot.

Display Woocommerce product discount in cart and checkout page after coupon is applied
<span position="button" tabindex="0" data-code="// Show Woocommerce product low cost in cart and checkout web page after coupon is utilized
add_filter( 'woocommerce_cart_item_subtotal', 'wpsh_coupon_discount', 100, 3 );
perform wpsh_coupon_discount( $subtotal, $cart_item, $cart_item_key ){

//Get product object
$_product = $cart_item['data'];
$line_subtotal_tax = $cart_item['line_subtotal_tax'];
if( $cart_item['line_subtotal'] !== $cart_item['line_total'] ) {
$line_tax = $cart_item['line_tax'];
$regular_price = $_product->get_regular_price()* $cart_item['quantity'];

$discountAmt=wc_price(($regular_price-$cart_item['line_subtotal']-$line_tax) + ($cart_item['line_subtotal']- $cart_item['line_total']));

$subtotal = sprintf( '<del>%s</del> <ins>%s</ins><p fashion="shade:inexperienced;font-size:14px;"><span fashion="shade:#242156;"><i class="fa fa-tags" aria-hidden="true"></i> Coupon utilized</span><br>You Saved: %s</p>', wc_price($regular_price), wc_price($cart_item['line_total'] + $line_tax),$discountAmt );
}else{

if( '' !== $_product->get_sale_price() ) {

$regular_price = $_product->get_regular_price() * $cart_item['quantity'];
$sale_price = $_product->get_sale_price() * $cart_item['quantity'];
$discountAmt=wc_price($regular_price-$sale_price);

$subtotal = sprintf( '<del>%s</del> <ins>%s</ins><p fashion="shade:inexperienced;font-size:14px;">You Saved: %s

// Show Woocommerce product low cost in cart and checkout web page after coupon is utilized
add_filter( 'woocommerce_cart_item_subtotal', 'wpsh_coupon_discount', 100, 3 );
perform wpsh_coupon_discount( $subtotal, $cart_item, $cart_item_key ){

	//Get product object
    $_product = $cart_item['data'];
	$line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    if( $cart_item['line_subtotal'] !== $cart_item['line_total'] ) {
	       $line_tax           = $cart_item['line_tax'];
		$regular_price = $_product->get_regular_price()* $cart_item['quantity'];
      
		$discountAmt=wc_price(($regular_price-$cart_item['line_subtotal']-$line_tax) + ($cart_item['line_subtotal']- $cart_item['line_total']));
 
        $subtotal = sprintf( '<del>%s</del> <ins>%s</ins><p fashion="shade:inexperienced;font-size:14px;"><span fashion="shade:#242156;"><i class="fa fa-tags" aria-hidden="true"></i> Coupon utilized</span><br>You Saved: %s</p>',  wc_price($regular_price), wc_price($cart_item['line_total'] + $line_tax),$discountAmt );
    }else{
		
		if( '' !== $_product->get_sale_price() ) {
         
		 $regular_price = $_product->get_regular_price() * $cart_item['quantity'];
			$sale_price = $_product->get_sale_price() * $cart_item['quantity'];
       $discountAmt=wc_price($regular_price-$sale_price);
	
 $subtotal = sprintf( '<del>%s</del> <ins>%s</ins><p fashion="shade:inexperienced;font-size:14px;">You Saved: %s</p>',  wc_price($regular_price), wc_price($_product->get_sale_price()),$discountAmt );
    }
	}
    return $subtotal;
}

How one can create Woocommerce coupon robotically after buy (and show it on the Thanks web page)?

One technique to inspire your clients to purchase extra is to offer them reductions. So, let’s see learn how to create Woocommerce coupon robotically after buy and show it on the Thanks web page.

<span position="button" tabindex="0" data-code="// Create Woocommerce Coupon Code Mechanically After Buy and show it on the thanks web page
add_action( 'woocommerce_before_thankyou', 'wpsh_create_coupon_code', 2 );
perform wpsh_create_coupon_code($order_id) {

$order = wc_get_order( $order_id );

$billing_first_name = $order->get_billing_first_name();
$coupon = new WC_Coupon();
$coupon->set_code( $billing_first_name . '20' ); // Coupon code will include billing first title and 20. For instance: John20
$coupon->set_amount( 20 ); // Low cost quantity
$coupon->set_discount_type( '%' ); // Low cost kind might be 'fixed_cart', '%' or 'fixed_product', defaults to 'fixed_cart'
$coupon->set_usage_limit( 1 ); // utilization restrict

$coupon->save();

echo '<div class="woocommerce-message">Right here’s your private coupon on your subsequent buy: ' . $billing_first_name . '20 which provides you 20% low cost.

// Create Woocommerce Coupon Code Mechanically After Buy and show it on the thanks web page
add_action( 'woocommerce_before_thankyou', 'wpsh_create_coupon_code', 2 );
perform wpsh_create_coupon_code($order_id) {

    $order = wc_get_order( $order_id );

    $billing_first_name = $order->get_billing_first_name();
    $coupon = new WC_Coupon();
    $coupon->set_code( $billing_first_name . '20' ); // Coupon code will include billing first title and 20. For instance: John20
    $coupon->set_amount( 20 ); // Low cost quantity
    $coupon->set_discount_type( '%' ); // Low cost kind might be 'fixed_cart', '%' or 'fixed_product', defaults to 'fixed_cart'
    $coupon->set_usage_limit( 1 ); // utilization restrict

    $coupon->save();

    echo '<div class="woocommerce-message">Right here’s your private coupon on your subsequent buy: ' . $billing_first_name . '20 which provides you 20% low cost.</div>';
}

How one can show a WooCommerce coupon enter area anyplace in your website with a shortcode?

Check out this screenshot under, and also you’ll see that I added Woocommerce enter area on my single product web page. So, let’s take a better look.

How to display a WooCommerce coupon input field anywhere on your site with a shortcode?
This snippet creates a shortcode [coupon_field] that you should utilize anyplace in your website.
<span position="button" tabindex="0" data-code="// Show a WooCommerce coupon enter area anyplace in your website with a shortcode
add_shortcode( 'coupon_field', 'display_coupon_field' );
perform display_coupon_field() {
if( isset($_GET['coupon']) && isset($_GET['redeem-coupon']) ){
if( $coupon = esc_attr($_GET['coupon']) ) {
$utilized = WC()->cart->apply_coupon($coupon);
} else {
$coupon = false;
}

$success = sprintf( __('Coupon "%s" Utilized efficiently.'), $coupon );
$error = __("This Coupon can't be utilized");

$message = isset($utilized) && $utilized ? $success : $error;
}

$output = '<div class="redeem-coupon"><type id="coupon-redeem">
<p><enter kind="textual content" fashion="width: 60%; float: left;" title="coupon" id="coupon"/>
<enter kind="submit" title="redeem-coupon" fashion="width: 40%;" worth="'.__('Redeem Supply').'" /></p>';

$output .= isset($coupon) ? '<p class="consequence">'.$message.'</p>' : '';

return $output . '</type>

// Show a WooCommerce coupon enter area anyplace in your website with a shortcode
add_shortcode( 'coupon_field', 'display_coupon_field' );
perform display_coupon_field() {
    if( isset($_GET['coupon']) && isset($_GET['redeem-coupon']) ){
        if( $coupon = esc_attr($_GET['coupon']) ) {
            $utilized = WC()->cart->apply_coupon($coupon);
        } else {
            $coupon = false;
        }

        $success = sprintf( __('Coupon "%s" Utilized efficiently.'), $coupon );
        $error   = __("This Coupon can't be utilized");

        $message = isset($utilized) && $utilized ? $success : $error;
    }

    $output  = '<div class="redeem-coupon"><type id="coupon-redeem">
    <p><enter kind="textual content" fashion="width: 60%; float: left;" title="coupon" id="coupon"/>
    <enter kind="submit" title="redeem-coupon" fashion="width: 40%;" worth="'.__('Redeem Supply').'" /></p>';

    $output .= isset($coupon) ? '<p class="consequence">'.$message.'</p>' : '';

    return $output . '</type></div>';
}

If you want to show Woocommerce coupon area on a single product web page then it is advisable to add additionally this snippet.

// Show coupon area in Woocommerce single product web page
add_action( 'woocommerce_product_meta_end', 'wpsh_coupon_field_on_single_product_page' );
perform wpsh_coupon_field_on_single_product_page() {
  echo 'Have a coupon? Enter it right here under.';
  echo do_shortcode('[coupon_field]');
}

How one can robotically apply Woocommerce coupon primarily based on cart amount?

For instance, let’s add a rule “If cart comprises a minimum of 4 merchandise or extra, then add robotically coupon “test20″”.

// Mechanically apply Woocommerce coupon primarily based on cart amount
add_action( 'woocommerce_before_calculate_totals', 'wpsh_autoapply_coupon', 25, 1 );
perform wpsh_autoapply_coupon( $cart ) {
    if ( is_admin() && ! outlined( 'DOING_AJAX' ) )
        return;

    // Setting and initialising variables
    $coupon = 'test20'; // Right here goes your coupon code
    $item_count = 4; // Right here goes the variety of objects
    $matched    = false;

    if( $cart->cart_contents_count >= $item_count ){
        $matched = true; 
    }

    // If circumstances are matched add coupon is just not utilized
    if( $matched && ! $cart->has_discount( $coupon )){
        // Apply the coupon code
        $cart->add_discount( $coupon );

        // Optionally show a message
        wc_add_notice( __('20% low cost coupon added'), 'discover');
    }
    // If circumstances usually are not matched and coupon has been appied
    elseif( ! $matched && $cart->has_discount( $coupon )){
        // Take away the coupon code
        $cart->remove_coupon( $coupon );

        // Optionally show a message
        wc_add_notice( __('Sorry, low cost is just not accessible'), 'error');
    }
}

How one can Apply a Woocommerce Coupon for Minimal Cart Whole?

This can be a barely completely different method than earlier one. On this instance we’ll arrange a coupon referred to as “test20” and it’ll give 20% low cost for orders with minimal 50 euros cart whole.

Now, if the cart whole is lower than 50 euros then the message “Get 20% off if you happen to spend greater than 50 euros” is robotically proven on Woocommerce cart and Checkout pages. If the minimal cart whole is greater than 50 euros then this coupon is robotically utilized and “You simply acquired 20% off your order!” is proven (see the screenshot).

How to Apply a Woocommerce Coupon for Minimum Cart Total
<span position="button" tabindex="0" data-code="// Apply a Woocommerce Coupon for Minimal Cart Whole
add_action( 'woocommerce_before_cart' , 'add_coupon_notice' );
add_action( 'woocommerce_before_checkout_form' , 'add_coupon_notice' );

perform add_coupon_notice() {

$cart_total = WC()->cart->get_subtotal();
$minimum_amount = 50; // Set your minimal cart whole
$currency_code = get_woocommerce_currency();
wc_clear_notices();

if ( $cart_total

// Apply a Woocommerce Coupon for Minimal Cart Whole
add_action( 'woocommerce_before_cart' , 'add_coupon_notice' );
add_action( 'woocommerce_before_checkout_form' , 'add_coupon_notice' );

perform add_coupon_notice() {

        $cart_total = WC()->cart->get_subtotal();
        $minimum_amount = 50; // Set your minimal cart whole
        $currency_code = get_woocommerce_currency();
        wc_clear_notices();

       if ( $cart_total < $minimum_amount ) {
              WC()->cart->remove_coupon( 'test20' ); // Change your copuon code.
              wc_print_notice( "Get 20% off if you happen to spend greater than $minimum_amount $currency_code!", 'discover' );
        } else {
              WC()->cart->apply_coupon( 'test20' );
              wc_print_notice( 'You simply acquired 20% off your order!', 'discover' );
        }
          wc_clear_notices();
}

How one can show Woocommerce discounted value on cart and checkout web page if coupon has been utilized?

Subsequent, let’s check out learn how to show Woocommerce discounted value on cart and checkout web page if coupon has been utilized. See the screenshot.

How to display Woocommerce discounted price on cart and checkout page if coupon has been applied?
<span position="button" tabindex="0" data-code="// Show Woocommerce discounted value on cart and checkout web page if coupon has been utilized?
add_filter( 'woocommerce_cart_item_subtotal', 'wpsh_display_coupon_discount', 99, 3 );
perform wpsh_display_coupon_discount( $subtotal, $cart_item, $cart_item_key ) {

$cart = WC()->cart;
$coupons = $cart->get_coupons();
// If no coupons, simply go together with subtotal.
if ( empty( $coupons ) ) {
return $subtotal;
}

// Set defaults.
$label = '';
$discounted_price = 0;
$amount_prev = 0;
$newsubtotal = '';
$iterator = 1;
$coupons_count = is_countable( $coupons ) ? depend( $coupons ) : 0;

foreach ( $coupons as $coupon ) {
$knowledge = $coupon->get_data();
$coupon_code = $knowledge['code'];
$quantity = $knowledge['amount'];
$kind = $knowledge['discount_type'];

if ( $cart->has_discount( $coupon_code ) && $coupon->is_valid() ) {

$label = __( 'Coupon: ', 'textdomain' ) . $coupon_code;
// Sequentially apply coupons is making use of subsequent coupon to already disconted value, not unique value.
$apply_seq = 'sure' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ? true : false;
// Value to be discounted – already discounted or unique.
$price_to_discount = ( $apply_seq && $discounted_price ) ? $discounted_price : $cart_item['data']->get_price();

// Calculate the low cost, relying on the low cost kind.
if ( '%' === $kind ) {
$discounted_price = $price_to_discount – ( $price_to_discount * ( ( $quantity + $amount_prev ) / 100 ) );
} elseif ( 'fixed_product' === $kind ) {
$discounted_price = $price_to_discount – ( $quantity + $amount_prev );
}

// Add the foreign money and html to new subtotal (after multiplied with amount).
$wc_html_subtotal = wc_price( $discounted_price * $cart_item['quantity'] );
// New subtotal for every coupon low cost and the ultimate newsubtotal.
if ( $iterator < $coupons_count ) {
$newsubtotal .= sprintf( '<div class="low cost"><small class="coupon-code">%s</small><s>%s</s></div>', $label, $wc_html_subtotal );
} else {
$newsubtotal .= sprintf( '<div class="low cost"><small class="coupon-code">%s</small>%s</div>', $label, $wc_html_subtotal );
}
}
// If coupons not utilized sequentially, apply all of the coupons mixed to the unique value.
$amount_prev = ! $apply_seq ? $quantity : 0;
$iterator++;
}
// Subtotal with new subtotal(s) added (utilized coupons).
$subtotal = sprintf( '<s>%s

// Show Woocommerce discounted value on cart and checkout web page if coupon has been utilized?
add_filter( 'woocommerce_cart_item_subtotal', 'wpsh_display_coupon_discount', 99, 3 );
perform wpsh_display_coupon_discount( $subtotal, $cart_item, $cart_item_key ) {

  $cart    = WC()->cart;
  $coupons = $cart->get_coupons();
  // If no coupons, simply go together with subtotal.
  if ( empty( $coupons ) ) {
    return $subtotal;
  }

  // Set defaults.
  $label            = '';
  $discounted_price = 0;
  $amount_prev      = 0;
  $newsubtotal      = '';
  $iterator         = 1;
  $coupons_count    = is_countable( $coupons ) ? depend( $coupons ) : 0;

  foreach ( $coupons as $coupon ) {
    $knowledge        = $coupon->get_data();
    $coupon_code = $knowledge['code'];
    $quantity      = $knowledge['amount'];
    $kind        = $knowledge['discount_type'];

    if ( $cart->has_discount( $coupon_code ) && $coupon->is_valid() ) {

      $label = __( 'Coupon: ', 'textdomain' ) . $coupon_code;
      // Sequentially apply coupons is making use of subsequent coupon to already disconted value, not unique value.
      $apply_seq = 'sure' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ? true : false;
      // Value to be discounted - already discounted or unique.
      $price_to_discount = ( $apply_seq && $discounted_price ) ? $discounted_price : $cart_item['data']->get_price();

      // Calculate the low cost, relying on the low cost kind.
      if ( '%' === $kind ) {
        $discounted_price = $price_to_discount - ( $price_to_discount * ( ( $quantity + $amount_prev ) / 100 ) );
      } elseif ( 'fixed_product' === $kind ) {
        $discounted_price = $price_to_discount - ( $quantity + $amount_prev );
      }

      // Add the foreign money and html to new subtotal (after multiplied with amount).
      $wc_html_subtotal = wc_price( $discounted_price * $cart_item['quantity'] );
      // New subtotal for every coupon low cost and the ultimate newsubtotal.
      if ( $iterator < $coupons_count ) {
        $newsubtotal .= sprintf( '<div class="low cost"><small class="coupon-code">%s</small><s>%s</s></div>', $label, $wc_html_subtotal );
      } else {
        $newsubtotal .= sprintf( '<div class="low cost"><small class="coupon-code">%s</small>%s</div>', $label, $wc_html_subtotal );
      }
    }
    // If coupons not utilized sequentially, apply all of the coupons mixed to the unique value.
    $amount_prev = ! $apply_seq ? $quantity : 0;
    $iterator++;
  }
  // Subtotal with new subtotal(s) added (utilized coupons).
  $subtotal = sprintf( '<s>%s</s> %s', $subtotal, $newsubtotal );

  return $subtotal;
}

Now, as a way to make it appear like the one you see on the screenshot above, add this piece of CSS to your Customizer >> Extra CSS space.

	.woocommerce desk.shop_table .product-subtotal s,
		.woocommerce desk.shop_table .product-total > s {
			font-size: 0.95em;
			font-weight: regular;
			margin: 0px !necessary;
			opacity: 0.7;
		}
		.woocommerce desk.shop_table .product-subtotal s,
		.woocommerce desk.shop_table .product-subtotal > span,
		.woocommerce desk.shop_table .product-total s,
		.woocommerce desk.shop_table .product-total > span {
			line-height: 1.4;
			margin: 5px;
		}
		.woocommerce desk.shop_table .product-subtotal > span,
		.woocommerce desk.shop_table .product-total > span {
			font-weight: daring;
		}
		.low cost {
			place: relative;
			show: block;
		}
		.low cost > * {
			show: inline-block;
		}
		.coupon-code {
			padding: 1px 4px 0px;
			border: 1px stable #ddd;
			line-height: 1.5;
			background: #fbf2e5;
			margin-right: 4px;
			text-transform: uppercase;
			font-size: 9px;
			font-weight: daring !necessary;
			border-radius: 4px;
			opacity: 0.8;
		}
		@media display screen and (max-width: 480px) {
			.coupon-code {
				show: none;
			}
		}

How one can set all Woocommerce transport charges to 0 if free transport coupon is used?

Woocommerce means that you can enable free transport if a coupon is used. This additionally signifies that it is advisable to arrange a free transport technique on your store.

With the assistance of this snippet you may set all transport charges to 0 if a free transport coupon is used. See the screenshot.

How to set all Woocommerce shipping rates to 0 if free shipping coupon is used?

// Set all Woocommerce transport charges to 0 if free transport coupon is used
add_filter( 'woocommerce_package_rates', 'wpsh_free_shipping_coupon', 20, 2 );
perform wpsh_free_shipping_coupon( $charges, $bundle ) {
    $has_free_shipping = false;

    $applied_coupons = WC()->cart->get_applied_coupons();
    foreach( $applied_coupons as $coupon_code ){
        $coupon = new WC_Coupon($coupon_code);
        if($coupon->get_free_shipping()){
            $has_free_shipping = true;
            break;
        }
    }

    foreach( $charges as $rate_key => $charge ){
        if( $has_free_shipping ){
            // For "free transport" technique (enabled), take away it
            if( $charge->method_id == 'free_shipping'){
                unset($charges[$rate_key]);
            }
            // For different transport strategies
            else {
                // Append charge label titles (free)
                $charges[$rate_key]->label .= ' ' . __('(free)', 'woocommerce');

                // Set charge price
                $charges[$rate_key]->price = 0;

                // Set taxes charge price (if enabled)
                $taxes = array();
                foreach ($charges[$rate_key]->taxes as $key => $tax){
                    if( $charges[$rate_key]->taxes[$key] > 0 )
                        $taxes[$key] = 0;
                }
                $charges[$rate_key]->taxes = $taxes;
            }
        }
    }
    return $charges;
}

How one can create a coupon programmatically in Woocommerce?

Only a easy snippet for many who need to create a coupon programmatically in Woocommerce.

// Create a coupon programmatically in Woocommerce
add_action('wp_loaded' , 'wpsh_create_coupon');
perform wpsh_create_coupon(){
    $coupon = new wc_coupon();
    if( !wc_get_coupon_id_by_code( 'yourcouponname20' ) ) { // Add your coupon title right here
        $coupon->set_code('yourcouponname20'); // Create coupon code
	    $coupon->set_discount_type( '%' ); // Low cost kind might be 'fixed_cart', '%' or 'fixed_product', defaults to 'fixed_cart'
	    $coupon->set_amount( 20 ); // Low cost quantity
	  	$coupon->set_usage_limit( 10 ); // Utilization restrict
        $coupon->save();        
    }
}

How one can delete WooCommerce coupons robotically after they expire?

So, you arrange an expiration date on your coupons, and you wouldn’t prefer to litter your database after these coupons have expired. Which implies, you want a snippet which lets you delete WooCommerce coupons robotically after they expire. Check out the snippet right here under. It robotically deletes these coupons 10 days after the expiration date .

PS! Line 13 is the one chances are you’ll have to tweak as a way to arrange the times quantity.

<span position="button" tabindex="0" data-code="// Delete WooCommerce coupons robotically after they expire
add_action( 'delete_expired_coupons', 'wpsh_delete_expired_coupons' );
perform wpsh_delete_expired_coupons() {

$args = array(
'posts_per_page' => -1,
'post_type' => 'shop_coupon',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'date_expires',
'worth' => strtotime( '-10 days', current_time( 'timestamp' ) ),
'evaluate' => '

// Delete WooCommerce coupons robotically after they expire
add_action( 'delete_expired_coupons', 'wpsh_delete_expired_coupons' );
perform wpsh_delete_expired_coupons() {

    $args = array(
        'posts_per_page' => -1,
        'post_type'      => 'shop_coupon',
        'post_status'    => 'publish',
        'meta_query'     => array(
            'relation'   => 'AND',
            array(
                'key'     => 'date_expires',
                'worth'   => strtotime( '-10 days', current_time( 'timestamp' ) ),
                'evaluate' => '<='
            ),
            array(
                'key'     => 'date_expires',
                'worth'   => '',
                'evaluate' => '!='
            )
        )
    );

    $coupons = get_posts( $args );

    if ( ! empty( $coupons ) ) {
        foreach ( $coupons as $coupon ) {
            wp_trash_post( $coupon->ID );
        }
    }
}

Associated Woocommerce hacks

  • How one can Customise Woocommerce Orders web page? (20 hacks)

  • How one can Cover Woocommerce Delivery Strategies (Conditionally) – A Full Information

  • How one can show Woocommerce my account tabs horizontally?

  • How one can Customise Woocommerce Admin Dashboard? 16 hacks

  • How one can Show Woocommerce Fee Strategies Conditionally? (14 hacks)

  • How one can Customise Woocommerce Inventory Standing? (17 hacks)

  • How one can Add Customized Endpoints in WooCommerce?

  • How one can Create Customized Product Badges for Woocommerce?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart
Scroll to Top