Skip to content

Instantly share code, notes, and snippets.

@Bobz-zg
Last active November 8, 2022 14:24
Show Gist options
  • Save Bobz-zg/29ec5fa13aafc46a969ecfdc47b2be06 to your computer and use it in GitHub Desktop.
Save Bobz-zg/29ec5fa13aafc46a969ecfdc47b2be06 to your computer and use it in GitHub Desktop.
Set woocommerce coupon to be available only for logged in users
<?php
add_filter( 'woocommerce_coupon_is_valid', function( $is_valid, $coupon ) {
/**
* Selected coupons allowed for logged in users only
*/
if ( in_array( $coupon->get_code() , ['loggedinonly', 'anothercoupontitle']) && ! is_user_logged_in() )
{
return false;
}
return $is_valid;
}, 100, 2 );
@makerovski
Copy link

Hi thank you for your code!

Can you maybe help me?

How do I set a message error if a not logged user try to use a code ?

I found this :

add_filter('woocommerce_coupon_error', function ( $message, $error_code, $coupon ) { return '<div>MESSAGE <a href="/mein-konto/">click here</a> </div>'; }, 10, 3 );

but it makes all errors show this message, also when the user tries to use a coupon that not exist.

I tried to use another filters like:

add_filter( 'woocommerce_coupon_error','coupon_error_message_change',10,3 );

function coupon_error_message_change($err, $err_code, $WC_Coupon) {
    switch ( $err_code ) {
        case $WC_Coupon::E_WC_COUPON_NOT_EXIST:
            $err = 'not exist';
    }
    return $err;
}

but do not work, the first error shows always.

@nicuvoicu
Copy link

nicuvoicu commented Nov 8, 2022

add_filter('woocommerce_coupon_error', function ($message, $error_code, $coupon) {
    if (in_array($coupon->get_code(), ['loggedinonly'])) {
        $message = '<div>Coupon is valid for registered users only. <a href="' . home_url('/register') . '">Register now!</a></div>';
    }

    return $message;
}, 10, 3);

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