latest stable versions: v150827 (changelog)

Old Forums (READ-ONLY): The community now lives at WP Sharks™. If you have an s2Member® Pro question, please use our new Support System.

Gift / Coupon Codes for s2member

Home Forums Community Forum Unofficial Extensions/Hacks Gift / Coupon Codes for s2member

Tagged: ,

This topic contains 2 replies, has 2 voices. Last updated by  Angie Gonzalez 3 years, 10 months ago.

Topic Author Topic
Posted: Wednesday Jul 18th, 2012 at 11:19 pm #19715

In relation to post:

This code will enable you to generate coupon codes and have your users activate them, without having to go through s2members payment systems. You’ll be able to update the user role.

– You can create coupons in any name you want (e.g. “FREEUPGRADE”, “PROMO4U”, etc).
– You can create coupons that can be redeemed X number of times.
– You can set expiration date for coupons.
– You can record the user ID and date of who redeemed the coupon and the blog owner receives a notification email.
– You can update user role or custom capabilities with this. It overwrites user role, but ADDS custom capabilities.

– If a user has a coupon that can be redeemed X number of times, they can consume all coupons by going back and punching it again (no benefit to them, but still burns through your coupon plan).

Next Versions:
– Enable GIFTing for customers: the plan is to sell access to a page (only accessed with a custom capability) that will enable a customer to extract 1 coupon and send it to whatever email they want (or print).

Code Description:

There are 3 pieces that you need for this to work:

1) Create a database in phpMyAdmin (details below). This will store your coupons. (I’m not covering the database creation etc).

2) Add a Function to your WP site that modifies the s2member user role and custom capabilities. (I’m not covering how to add the function to your site)

3) Create a Form page that receives the coupon, performs validation/error handling and updates the user role. (I’m not getting into how to setup this page or where to put the file in this post)

This is the code:


table name: wp_fjcoupons

ID int(20), ID for the coupon. Auto increment
C_NUM text, Coupon code, *REQUIRED FIELD*
A_TYPE text, access type, *REQUIRED FIELD*
A_CAP text, custom capabilities separated by coma, can be null
TIME_MAX date, when the coupon expires, can be null
DIST_NAME text, keep a record of who distributed your coupon, can be null
TIME_USE date, time the coupon was used, can be null
USER_ID int(20), the user that redeemed the coupon, can be null

* You can repeat C_NUM across multiple lines (e.g. “FREEACCESS”) and this will give you multiple redemptions for that coupon (1 per line)


Author: Angie Gonzalez
Date: 7-18-2012
Feel free to use/update/augment etc..

function FJ_Activate_Coupon($userID, $RoleStr, $RoleB = true) {  // userID is the current user redeeming the coupon, RoleStr is what you want to update, and RoleB is a boolean for updating user role or custom capability.

         $user = new WP_User($userID);     // create a User Object

         if ($user->role[0]!="administrator") {
           /* Modifies custom registration fields (useful when the field you want to update is present at registration)
             $custom_fields = get_user_option("s2member_custom_fields");
             $custom_fields["coupon_id"] = $CouponID;
             update_user_option($user->ID, "s2member_custom_fields", $custom_fields);
           if ($RoleB === true) {  //modify user role
               // This can only modify 1 role or capability at a tiem.  You need to run the funcion with 1 parameter.
               $user->set_role($RoleStr);  // subscriber, or s2member_level[1 2,3,4]
           else {  //modify custom capability
               $user->add_cap("access_s2member_ccap_".$RoleStr ); // adds custom capability
              $expire_on = strtotime("+2 years");      // establish the EOT for the role
                            update_user_option ($user->ID, "s2member_auto_eot_time", $expire_on);
           //return "ID: ".$user->ID." Update: ".$user->roles[0]." Bool: ".$RoleB;  // Ignore:  lines I used for testing
         } else {
           //return "No ha corrido el codigo porque eres Admin"; //  Ignore: lines I used for testing

Form (Coupon) page:

fjcoupons = $table_prefix.'fjcoupons';       // add our custom coupon table into de database

if(isset($_POST['submitted'])) {

        if(trim($_POST['contactName']) === '') {   // start of IF
		// validate that the form field has a value.
                $form_ErrorMsg = 'Introduzca un valor.';
		$hasError = true;
	} else {
		// if the form field has a value, continue with code
                $name = trim($_POST['contactName']);
                $name = strtoupper($name);

                $cRow= $wpdb->get_row( $wpdb->prepare(  // make a query to extract the coupon, it will only return if ther user_id field is empty (no one has used it).  The row metod extracts the first line for the coupon match (this enables you to have the same coupon code in various rows, so you can control how many times it can be redeemed).
                                                SELECT *
                                                FROM $wpdb->fjcoupons
                                                WHERE (c_num = '%s' AND user_id IS NULL)

                ) );
                $cVal = $wpdb->get_row( $wpdb->prepare(    // make a query to extract the coupon, regardless of used or not.  Row method returns one line (even if there are multiple for the query)
                                                SELECT *
                                                FROM $wpdb->fjcoupons
                                                WHERE C_NUM = '%s'
                ) );
                if ($cRow->ID != NULL) {     // if cRow (our first query) has a value, it means the coupon exist and has not been used.
                   if (strtotime($cRow->TIME_MAX) > strtotime("now")) {       // check to see if the coupon is still valid
                     $fjUserID=get_current_user_id();   // obtain the logged in users ID
                     $cRow->USER_ID = $fjUserID;
                     $cRow->TIME_USE = current_time('mysql');     // generate a time stamp to record when the coupon has been redeemed (mysql format).
                     $form_ErrorMsg = 'El codigo ha sido activado.';    // This is the message we'll use after the customer activates the coupon button.
                     $wpdb->update(      // we update the database with the user that has redeemed the coupon with date.
                               'USER_ID' => $cRow->USER_ID,  //integer
                               'TIME_USE' => $cRow->TIME_USE,  //date-integer
                         array( 'ID' => $cRow->ID ),
                               '%d',      // integer
                               '%s',      // string
                         array( '%d' )
                     // Let's change the users role...  the Activate Coupons can only update one value at a time, so chec if coupon has Role Type such as s2member_level1 (A_TYPE) or Capability (A_CAP).
                     if ($cRow->A_TYPE != NULL) {
                     if ($cRow->A_CAP != NULL) {
                       $Cap_Array = explode(",",$cRow->A_CAP);     // if capabilities exist, they are store in the database separated with commas. This line converts it into array.
                       for($i = 0; $i < count($Cap_Array); ++$i)  {      // loop to update each capability with the Activate Coupons function.

                   } else {   // the coupon exist and has not been utilized, but its no longer valid (exceeded TIME_MAX)
                     $form_ErrorMsg = 'El codigo ha vencido.';
                     $hasError = true;
                } else {
                   If($cVal === NULL) {     // the coupon does not exist
                     $form_ErrorMsg = 'El codigo no es valido.';
                     $hasError = true;
                   } else {               // the coupon exist, but it has already been redeemed and is no longer available.
                     $form_ErrorMsg = 'El codigo ya ha sido utilizado el maximo numero de veces.';
                     $hasError = true;
	}  // end of IF

	if(!isset($hasError)) {       // Send an email to Blog owner tp notify coupon redemption.

                $emailTo = '';
                $subject 	= 'Mensaje enviado por: '.$name;
		$body 		= "Nombre: $name nEmail: $email";
		$headers 	= 'From: Bebé Semillitas ' . "rn" . 'Reply-To: ' . $email;

                    if(mail($emailTo, $subject, $body, $headers))  {
                      $emailSent = true;
    		    } else {

} ?>


							<div class="thanks">
								<p><span style="color: #0000ff"></span></p>
								<p class="error"><span style="color: #ff0000"></span><p>

						&lt;form action=&quot;" id="contactForm" method="post"&gt;

								<label for="contactName">Codigo</label>
								&lt;input type=&quot;text&quot; name=&quot;contactName&quot; id=&quot;contactName&quot; value=&quot;" class="required requiredField" /&gt;
									<span class="error"></span>


	</div><!-- .content -->
	ID, 'page_options', true );
            $sidebar_opts = $page_opts['sidebar_opts'];
	if ( ( $sidebar_opts == 'right' ) &amp;&amp; ( !( $sidebar_opts == 'left' || $sidebar_opts == 'none' ) ) ){
	elseif ( ( $crz_sidebar == 'right' ) &amp;&amp; ( !( $sidebar_opts == 'left' || $sidebar_opts == 'none' ) ) ) {
    </div><!-- .primary_wrap -->
</div><!-- .primary -->
  • This topic was modified 4 years, 5 months ago by  Angie Gonzalez.
  • This topic was modified 4 years, 5 months ago by  Angie Gonzalez.
  • This topic was modified 3 years, 4 months ago by  Angie Gonzalez.

List Of Topic Replies

Viewing 2 replies - 1 through 2 (of 2 total)
Author Replies
Author Replies
Posted: Sunday Mar 10th, 2013 at 2:02 pm #44218

Hey there – just curious; this is a way you can create coupons for someone but not really a way that user 1 can buy a certificate that can be gifted to user 2 correct?

Posted: Monday Mar 11th, 2013 at 5:25 pm #44281

You can add a way for a customer to buy a coupon as a “gift”. I’ve done this on my site, but for simplicity, I’ll only describe the way I did it.

I did it this way:

1) I added additional fields to the database:
GFT: marks the code as available to be send out as gift.
GFT_REC: marks the name of the recipient.
GFT_REC_MAIL: enters the address of receiving customer

2) I uploaded several coupon codes to the database and marked the GIFT column with a “1”. These are the coupon codes available to be sent as a gift.

3) I make customer buy a gift “subscription”, it is a Custom Capabilities (e.g. gift_cap) that gives them access to a gift giving page.

4) Once they log in, I use conditionals to show them a button that says “send gift coupon”, and they go to a Form.

5) The Form validates that the customer has the capability to send out gifts, grabs a gift code from the database, and sends an email to receiver and sender.

Hope this helps.

Viewing 2 replies - 1 through 2 (of 2 total)

This topic is closed to new replies. Topics with no replies for 2 weeks are closed automatically.

Old Forums (READ-ONLY): The community now lives at WP Sharks™. If you have an s2Member® Pro question, please use our new Support System.

Contacting s2Member: Please use our Support Center for bug reports, pre-sale questions & technical assistance.