How to enable a referral link for users with active Subscription

READ FIRST: This code needs to be added at the end of the functions.php file. If you are familiar with editing functions.php, feel free to continue reading. If you haven’t done this before, adding this code in the wrong place might bring the site down and the only way to access it is by editing functions.php file again via FTP. Feel free to contact us if you need help!

If you want to allow referral link only to a user that has an active WooCommerce subscription, add the following code to the functions.php file:

/**
 * Check if a user has an active WooCommerce subscription.
 * Requires WooCommerce Subscriptions (wcs_user_has_subscription).
 */
if ( ! function_exists( 'my_has_active_subscription' ) ) {
	function my_has_active_subscription( $user_id = 0 ) {
		// Default to current user
		if ( empty( $user_id ) && is_user_logged_in() ) {
			$user_id = get_current_user_id();
		}

		// Not logged in or no id
		if ( empty( $user_id ) ) {
			return false;
		}

		// If Subscriptions isn't active, treat as no active subscription
		if ( ! function_exists( 'wcs_user_has_subscription' ) ) {
			return false;
		}

		return (bool) wcs_user_has_subscription( $user_id, '', 'active' );
	}
}

/**
 * Show RAF code only to users with an active subscription.
 */
add_filter( 'wpgens_raf_code', 'gens_raf_code_active_sub_only', 10, 1 );
function gens_raf_code_active_sub_only( $raf_code ) {
	$user_id = get_current_user_id();

	if ( ! my_has_active_subscription( $user_id ) ) {
		return 'Referral code is available only to customers with an active subscription.';
	}

	return $raf_code;
}

/**
 * Show RAF link only to users with an active subscription.
 */
add_filter( 'wpgens_raf_link', 'gens_raf_link_active_sub_only', 10, 3 );
function gens_raf_link_active_sub_only( $raf_link, $referral_id, $type ) {
	$user_id = get_current_user_id();

	if ( ! my_has_active_subscription( $user_id ) ) {
		return 'Referral link is available only to customers with an active subscription.';
	}

	return $raf_link;
}

/**
 * Hide the RAF "My Account" tab if user doesn't have an active subscription.
 * (Matches your previous behavior of removing the tab for disallowed users.)
 */
add_action( 'wp', 'wpgens_custom_account_tabs_active_sub_only' );
function wpgens_custom_account_tabs_active_sub_only() {
	// Only act for logged-in users
	if ( ! is_user_logged_in() ) {
		return;
	}

	$user_id = get_current_user_id();

	if ( ! my_has_active_subscription( $user_id ) ) {
		if ( class_exists( 'WPGens_RAF' ) ) {
			$gens_plugin = WPGens_RAF::instance();
			remove_filter(
				'woocommerce_account_menu_items',
				array( $gens_plugin->my_account, 'gens_account_menu_item' ),
				10
			);
		}
	}
}
Browse our plugins

Lightweight WooCommerce plugins built for speed. No bloat, no frameworks -- just clean code that works.

View all plugins