Membership 2 is an awesome plugin to sell your content. That being said, you can charge your members to see your site content.

If you want to give discount, you can use Coupon addon. You have to enable from Membership 2 > Addons and then you can create coupons and share with your users. Today I will show you a trick to share coupon embedded with URL. You can share your URl like domain.com/?coupon=XXXX and the XXXX coupon will be automatically applied on checkout.

Let’s look at the code:

<?php
/**
* Configuration: Just set the query variable name in the first line – DEFINE
* In the example, I have used coupon.
* So, in my case the URL would be: domain.com/?coupon=AAAA
* Where AAAA is the M2 coupon
*/
if( ! defined( 'M2_COUPON' ) ) define( 'M2_COUPON', 'coupon' );
add_action( 'init', 'm2_sess_init' );
function m2_sess_init() {
if( ! isset( $_SESSION ) ) {
session_start();
}
}
add_action( 'template_redirect', 'm2_check_coupon' );
function m2_check_coupon() {
if( isset( $_REQUEST[M2_COUPON] ) && $_REQUEST[M2_COUPON] != '' ) {
$_SESSION['M2_COUPON'] = $_REQUEST[M2_COUPON];
}
}
add_action( 'wp_footer', 'm2_apply_coupon' );
function m2_apply_coupon() {
if( isset( $_SESSION['M2_COUPON'] ) && $_SESSION['M2_COUPON'] != '' ) {
?>
<style>
.membership-coupon{display: none;}
</style>
<script type="text/javascript">
jQuery(function($) {
if( ! $('.membership-coupon .ms-alert-box').length ){
$('#coupon_code').val('<?php echo $_SESSION['M2_COUPON'] ?>');
$('#apply_coupon_code').click();
}
});
</script>
<?php
}
}

view raw
code.php
hosted with ❤ by GitHub

You can add those codes in your functions.php in the theme, if you think your theme won’t be changed. Otherwise mu-plugins is the best solution. To use mu-plugins, go to /wp-content/ and find the folder with name ‘mu-plugins’. If there is no folder in that name, then create a folder, name it ‘mu-plugins’, create a file inside that, give any name you like and paste the code in there. You don’t need to activate that plugin. Mu-plugins means must use plugins, so it will be activated automatically always. If you use mu-plugins then add a php start tag at the beginning of the code.

Leave a Reply