I'm trying to add a basic IF-statement to a PHP code snippet but my PHP knowledge is very limited and I didn't have much success until now (I tried different variations on IF-statements which I found in other code snippets).
The company that originally created the code explained me in the code snippet where to add the IF-statement, what kind of IF-statement I need (if the coupon code begins with 'affiliate-credit' return true) and also told me I should work with the variable called $coupon
(this variable contains the name of the coupon).
Here is the code snippet:
<?php
/**
* Plugin Name: AffiliateWP - Block WooCommerce Assigned Affiliate Coupon If Affiliate Purchasing
* Plugin URI: http://affiliatewp.com
* Description: Prevents assigned affiliate coupon codes from being used on the WooCommerce order if the affiliate is the purchaser
* Author: AffiliateWP
* Author URI: https://affiliatewp.com
* Version: 1.0
*/
/**
* Make assigned coupon invalid if customer is an affiliate.
*/
function affwp_custom_block_affiliate_coupon_if_customer_affiliate( $condition, $coupon, $vars ) {
if ( ! function_exists( 'affiliate_wp' ) ) {
return $condition; // Make sure AffiliateWP is installed, otherwise just return.
}
$current_user_id = get_current_user_id();
if ( empty( $current_user_id ) ) {
return $condition; // Probably not logged in, just return.
}
if ( ! affwp_is_affiliate( $current_user_id ) ) {
return $condition; // Not an affiliate, just return.
}
if ( empty( $coupon->id ) ) {
$coupon = affwp_get_coupon( $coupon->code );
// Add IF statement here that if the coupon code begins with 'affiliate-credit' return true to allow store credit coupons.
if ( false !== $coupon && affwp_get_affiliate_user_id( $coupon->affiliate_id ) === $current_user_id ) {
return false; // Dynamic coupon assigned to this affiliate, disallow the coupon.
}
}
$is_tracked_coupon = get_post_meta( $coupon->id, 'affwp_discount_affiliate', true );
if ( affwp_get_affiliate_user_id( $is_tracked_coupon ) === $current_user_id ) {
return false; // Coupon assigned to this affiliate, disallow the coupon.
}
return $condition;
}
add_filter( 'woocommerce_coupon_is_valid', 'affwp_custom_block_affiliate_coupon_if_customer_affiliate', 10, 3 );
To give you some more info about what this code snippet does:
- This code snippet blocks affiliates to use discount coupon codes for new clients themselves (because they already got a discount when registering)
What I'm trying to accomplish by adding that IF-statement:
- Add an exception to the code snippet so that coupons for which the coupon code starts with the text 'affiliate-credit' are not blocked (so an affiliate is allowed to use that coupon).
I understood it should be a very easy line of code to write for a PHP developer but I didn't have much success until now since my PHP knowledge is very limited.