Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce - Create a coupon via PHP
$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
@abdulawal39

This comment has been minimized.

Copy link

abdulawal39 commented Apr 25, 2013

Can you please tell me where it should be placed ?

@jhodgski

This comment has been minimized.

Copy link

jhodgski commented Jun 20, 2013

You would put this code inside a new function in your functions.php file. It's up to you when you'd need call that function. E.g., I am using it so that when a certain page loads, the function is called to create the coupon and then email the code to the user. If you wanted to show the new code on screen, you could quite easily have the function return 'UNIQUECODE'.

NB - Normally, you'd create a coupon by logging in to yoursite.com/wp-admin and going WooCommerce > Coupons > Add Coupon.

@monetizer

This comment has been minimized.

Copy link

monetizer commented Dec 30, 2013

I created a new function in functions.php and tried to call it in another page but it never showed the coupon and even coupon wasn't created as i see nothing in WooCommerce > Coupons

Am i doing something wrong or the code is not working anymore?

@emanweb

This comment has been minimized.

Copy link

emanweb commented Feb 21, 2014

I have done this with some changes. Here's my code on functions.php (then I created a private page where i call this function and it generates the coupon automatically.)

/* generate $15 off coupons */
function generate_coupons15 () {
$coupon_code = substr( "abcdefghijklmnopqrstuvwxyz123456789", mt_rand(0, 50) , 1) .substr( md5( time() ), 1); // Code
$coupon_code = substr( $coupon_code, 0,10); // create 10 letters coupon
$amount = '15'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '$15 off coupon',
    'post_excerpt' => '$15 off coupon',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '1' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'no' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );      
update_post_meta( $new_coupon_id, 'exclude_sale_items', 'no' );     
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );      
update_post_meta( $new_coupon_id, 'product_categories', '' );       
update_post_meta( $new_coupon_id, 'exclude_product_categories', '' );       
update_post_meta( $new_coupon_id, 'minimum_amount', '' );       
update_post_meta( $new_coupon_id, 'customer_email', '' );       

return $coupon_code;

}
@macttu

This comment has been minimized.

Copy link

macttu commented Jun 10, 2014

Would it be possible to use this code to automatically create a coupon code at checkout using the customer's "username" as the coupon code? I want it to be easy to remember for the customers so they can share the coupon codes......I have an affiliate program based on their coupon codes.

Ex. I create username "Mac" at checkout(username required on my site) and instantly coupon code "Mac" would be generated. This coupon could be used unlimited times and would be for 20% Off. If user name "Tim" is used, "Tim" would become a 20% Off coupon code etc.

Any help would be greatly appreciated, thanks in advance!

Mac

@mdroca

This comment has been minimized.

Copy link

mdroca commented Nov 1, 2014

Hello, I would like to know if is possible add more things here. I would like one code to disallow coupon when COD payment is used. Is possible?? What do I need to do??

@ketanzluck

This comment has been minimized.

Copy link

ketanzluck commented Oct 12, 2017

Hello,

I want to generate woocommerce coupon code dynamically.

My requirements is that after complete the order automatically generate one coupon code in admin side woocommerce coupon code list for particular product.

So any one know my above requirement solutions then please help me.

Thanks,
Ketan.

@Arzouni

This comment has been minimized.

Copy link

Arzouni commented Dec 3, 2017

for some reason i am getting that wp_insert_post is undefined after i added some code to this function,
please take a look at my code if you may let me know what i am doing wrong, just to let you know, this function is in a separate like which is included in functions.php and i am posting to that file using jQuery.post() from index.php
this is code:
`<?php

$subEmail = isset($_POST['subEmail']) ? $_POST['subEmail'] : null;

if($subEmail){
    justDoIt($subEmail);
}

function justDoIt($subEmail){

    define( 'SHORTINIT', true );
    // local
    require_once( $_SERVER['DOCUMENT_ROOT'] . '/wordpress/wp-load.php' );
    // live
    // require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
    global $wpdb;

    //Check if $subEmail is in DB
    $emailsQuery = 'SELECT meta_value FROM wp_postmeta WHERE meta_key = "_field_newsletteremail"';

    $dbEmails = $wpdb->get_results( $emailsQuery );

    foreach($dbEmails as $emailObj){
        if($subEmail === $emailObj->meta_value){
            echo "exists";
            die();
        }
    }
    //else create a coupon for him
    $couponCodeValue = $subEmail.time();
    $couponCodeValue = str_replace(' ', '', $couponCodeValue);
    $couponCodeValue = md5($couponCodeValue);

    //Get Existing Coupons we created
    $dbCoupons = $wpdb->get_results( 'SELECT post_title FROM wp_posts WHERE post_type = "shop_coupon" AND post_status = "publish"' );
    $x = 0;
    $y = 6;
    $couponCodeSixValue = substr($couponCodeValue, $x , $y);

    for($y; $y < strlen($couponCodeValue); $y++){
        //if code found generate new one, else just us the current
        if($dbCoupons[$i]->post_title === $couponCodeSixValue){
            $couponCodeSixValue = substr($couponCodeValue, ($x+1) , ($y+1));
        }
        $x++;
    }

    imagineme_create_coupon($couponCodeSixValue);

}


function imagineme_create_coupon( $couponCodeSixValue ){
    
    $coupon_code = $couponCodeSixValue; // Code
    $amount = '10'; // Amount
    $discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
                        
    $coupon = array(
        'post_title' => ''.$coupon_code,
        'post_content' => '',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type'		=> 'shop_coupon'
    );
    $new_coupon_id = wp_insert_post( $coupon );
                        
    // Add meta
    update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
    update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
    update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
    update_post_meta( $new_coupon_id, 'product_ids', '' );
    update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
    update_post_meta( $new_coupon_id, 'usage_limit', '1' );
    update_post_meta( $new_coupon_id, 'expiry_date', '' );
    update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
    update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

    echo $coupon_code;
}

?>`

@pdchaudhary

This comment has been minimized.

Copy link

pdchaudhary commented Apr 27, 2019

for expiry_date use this
//$date should be in timestamp
update_post_meta( $new_coupon_id, 'date_expires',$date );

@alvinarichard

This comment has been minimized.

Copy link

alvinarichard commented Sep 13, 2019

This is my code and I am trying to add a coupon for my online store but it's not working

add_action( 'woocommerce_before_cart', 'sh_coupons_matched' );
function sh_coupons_matched() {
global $woocommerce;
$sh_coupon = 'OnlineShop';
if ( $woocommerce->cart->has_discount( $sh_coupon ) ) return;
foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
$autocoupon = array( 65 );
if( in_array( $values['product_id'], $autocoupon ) ) {
$woocommerce->cart->add_discount( $cw_coupon );
wc_print_notices();
}
}
}

I have followed this WooCommerce coupon code tutorial to implement the whole process

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.