Home / Archive / MemberPress: Require Coupon Code for Specific Free Memberships
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Require Coupon Code for Specific Free Memberships

The code snippet should be updated to specify the membership ID for which the coupon code is required. The dummy ID of 123 should be replaced with the ID of the actual membership on this line:

$GLOBALS[‘free_memberships_require_coupon’] = array(123);

The code snippet can also be applied to several memberships by adding multiple membership IDs separated by a comma on the same line:
$GLOBALS[‘free_memberships_require_coupon’] = array(123, 456);

The error message can be adjusted by modifying the A valid coupon code is required to sign up for this membership. error text on this line:

$errors[] = ‘A valid coupon code is required to sign up for this membership.’;

In addition, the code snippet will change the coupon field label text. The filed label can be adjusted by modifying the Coupon Code (Required)* label text on this line:
$(‘input[name=“mepr_coupon_code”]‘).before(‘Coupon Code (Required)*’);

Code Preview
php
<?php
// CHANGE this array - should be a comma separated list of Membership ID's to apply the signup codes to
$GLOBALS['free_memberships_require_coupon'] = array(123);
function make_coupon_mandatory_free_membership($errors) {
	if(!isset($_POST['mepr_coupon_code']) || trim($_POST['mepr_coupon_code']) == '' && in_array($_POST['mepr_product_id'], $GLOBALS['free_memberships_require_coupon'])) {
		$errors[] = 'A valid coupon code is required to sign up for this membership.';
	}
	return $errors;
}
add_filter('mepr-validate-signup', 'make_coupon_mandatory_free_membership');
// Needed to show hidden coupon field on free memberships
function show_coupon_field_free_membership() {
	$is_free_membership = false;
	foreach($GLOBALS['free_memberships_require_coupon'] as $membership_id) {
		if(is_single($membership_id)) {
			$is_free_membership = true;
		}
	}
	if($is_free_membership):
		?>
		<script type="text/javascript">
			(function($) {
				$(document).ready(function() {
					// Not needed for free memberships as coupon field is hidden and no link to enable it
					// Uncomment for non-free memberships though
					// $('.mepr-signup-form .have-coupon-link').trigger('click');
					
					$('input[name="mepr_coupon_code"]').attr("type", "text");
					$('input[name="mepr_coupon_code"]').before('<label>Coupon Code (Required)*</label>');
				});
			})(jQuery);
		</script>
		<?php
	endif;
}
add_action('wp_footer', 'show_coupon_field_free_membership');

Comments

Add a Comment