Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mikejolley
Created October 28, 2012 19:28
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save mikejolley/3969579 to your computer and use it in GitHub Desktop.
Save mikejolley/3969579 to your computer and use it in GitHub Desktop.
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' );
@Arzouni
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
Copy link

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

@alvinarichard
Copy link

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

@alexcitos
Copy link

Hi!

If I want a coupon to be generated at the time of completing the payment and that coupon is the phone number at checkout. how can I do this?

@dcx15
Copy link

dcx15 commented Jun 16, 2020

@mikejolley, is this code still correct for WC4?

@mikejolley
Copy link
Author

@dcx15 yikes it's 8 years old but it should work. However, I'd suggest looking into using the WC_Coupon class instead. https://docs.woocommerce.com/wc-apidocs/class-WC_Coupon.html

@dcx15
Copy link

dcx15 commented Jun 17, 2020

Thanks for confirming Mike!

For anyone else that stumbled on this gist via Google, I found this answer on SO useful https://stackoverflow.com/a/61874195. All of the other blog posts and SO answers seem to be very outdated in Google results.

@redifmail
Copy link

How can we add something like add X quantity of any product and get Y % off?

@Stevemoretz
Copy link

Better using the wc_coupon instance with its save method now.

@CoachDom
Copy link

CoachDom commented Oct 26, 2023

@mikejolley Does this work in 2023? I'm just starting a new store with my own designs and I can't really afford to pay for those 50$ a month plugins (not before I will actually start making some money on this :D)
Thank you for all the effort you put in this so far!
Dom

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment