Last active
November 8, 2022 14:24
-
-
Save Bobz-zg/29ec5fa13aafc46a969ecfdc47b2be06 to your computer and use it in GitHub Desktop.
Set woocommerce coupon to be available only for logged in users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
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
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:
but do not work, the first error shows always.