Home / eCommerce / AffiliateWP — Block Referrals for Existing Customers
Duplicate Snippet

Embed Snippet on Your Site

AffiliateWP — Block Referrals for Existing Customers

Prevents AffiliateWP from generating referral commissions for returning customers. Commissions will only fire on a customer's first-ever order. Works for both logged-in and guest customers, and is compatible with custom order statuses from third-party plugins (e.g. WooCommerce Lottery). Uses the affwp_integration_create_referral filter.

Code Preview
php
<?php
/**
 * Block AffiliateWP referrals for existing WooCommerce customers.
 *
 * Allows referral commissions only on a customer's first-ever order.
 * Any returning customer will not generate a referral, regardless of
 * affiliate links clicked or coupons used.
 *
 * Install via WPCode > Code Snippets > Add Snippet > PHP Snippet > Run Everywhere.
 */
function my_affwp_no_referral_for_existing_customers( $allow, $referral_args ) {
    if ( ! function_exists( 'wc_get_order' ) || ! $allow ) {
        return $allow;
    }
    $order_id = ! empty( $referral_args['reference'] ) ? absint( $referral_args['reference'] ) : 0;
    if ( ! $order_id ) {
        return $allow;
    }
    $order = wc_get_order( $order_id );
    if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
        return $allow;
    }
    $customer_id   = (int) $order->get_customer_id();
    $billing_email = $order->get_billing_email();
    $customer      = $customer_id > 0 ? $customer_id : $billing_email;
    if ( empty( $customer ) ) {
        return $allow;
    }
    // Fetch every order status registered on the site, including custom
    // statuses added by third-party plugins like WooCommerce Lottery.
    $all_statuses = array_map(
        function( $s ) { return str_replace( 'wc-', '', $s ); },
        array_keys( wc_get_order_statuses() )
    );
    // Check for any previous order from this customer, excluding the current one.
    $previous_orders = wc_get_orders( array(
        'customer' => $customer,
        'exclude'  => array( $order_id ),
        'status'   => $all_statuses,
        'limit'    => 1,
        'return'   => 'ids',
    ) );
    if ( ! empty( $previous_orders ) ) {
        return false; // Returning customer — block the referral.
    }
    return $allow;
}
add_filter( 'affwp_integration_create_referral', 'my_affwp_no_referral_for_existing_customers', 10, 2 );

Comments

Add a Comment