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!
To hide the “Refer a friend” tab on the “My Account” page for non-subscription users and only show it for users with active or pending cancellation subscriptions, you can copy the code below to functions.php
add_filter('wpgens_raf_code', 'gens_raf_code', 10, 1);
function gens_raf_code($raf_code) {
$current_user = wp_get_current_user();
if (!user_has_active_subscription($current_user->ID)) {
return 'Referral code is available only to subscription users';
}
return $raf_code;
}
add_filter('wpgens_raf_link', 'gens_raf_link', 10, 3);
function gens_raf_link($raf_link, $referral_id, $type) {
$current_user = wp_get_current_user();
if (!user_has_active_subscription($current_user->ID)) {
return 'Referral link is available only to subscription users';
}
return $raf_link;
}
add_action('wp', 'wpgens_custom_account_tabs');
function wpgens_custom_account_tabs(){
$current_user = wp_get_current_user();
if (!user_has_active_subscription($current_user->ID)) {
$gens_plugin = WPGens_RAF::instance();
remove_filter('woocommerce_account_menu_items', array($gens_plugin->my_account, 'gens_account_menu_item'), 10);
}
}
function user_has_active_subscription($user_id) {
if (function_exists('wcs_user_has_subscription')) {
return wcs_user_has_subscription($user_id, '', 'active') || wcs_user_has_subscription($user_id, '', 'pending-cancel');
}
return false;
}
Explanation: #
user_has_active_subscription
function: This function checks if the user has an active or pending cancellation subscription using thewcs_user_has_subscription
function provided by WooCommerce Subscriptions.- Filters for referral code and link: These filters now check if the user has an active subscription before returning the referral code or link.
- Custom account tabs: This action checks if the user has an active subscription before removing the “Refer a friend” tab from the account menu.
Make sure that WooCommerce Subscriptions is installed and activated, as this code relies on its functions.