How to apply a coupon programmatically in Woocommerce?

You can apply a coupon programmatically in WooCommerce using the WC_Discounts class provided by WooCommerce. Here’s a code snippet that demonstrates how to apply a coupon programmatically:

php
Copy code
// Load WooCommerce functions
require_once( ABSPATH . ‘wp-load.php’ );

// Initialize WooCommerce
if ( ! function_exists( ‘WC’ ) ) {
include_once( dirname( __FILE__ ) . ‘/wp-content/plugins/woocommerce/woocommerce.php’ );
}
WC()->initialize();

// Coupon code to apply
$coupon_code = ‘your_coupon_code’;

// Get the WC_Coupon object
$coupon = new WC_Coupon( $coupon_code );

// Check if the coupon is valid
if ( $coupon->is_valid() ) {
// Apply the coupon to the current user’s cart
$coupon_result = WC()->cart->apply_coupon( $coupon_code );

// Check if the coupon was applied successfully
if ( $coupon_result === true ) {
echo “Coupon applied successfully.”;
} else {
echo “Failed to apply coupon.”;
}
} else {
echo “Coupon is not valid.”;
}
Replace ‘your_coupon_code’ with the actual coupon code you want to apply. This script first checks if the coupon is valid, then applies it to the current user’s cart using WC()->cart->apply_coupon(). Finally, it checks if the coupon was applied successfully and outputs a message accordingly.

Make sure to include this code in a suitable place within your WordPress environment, such as a custom plugin or a theme’s functions.php file.

Please note that running this code outside the context of a WordPress request (e.g., in a standalone PHP script) might require additional setup to properly load WordPress and WooCommerce functionalities.

You were not leaving your cart just like that, right?

Enter your details below to save your shopping cart for later. And, who knows, maybe we will even send you a sweet discount code :)

× How can I help you?