Hide specific product variations from unlogged users in WooCommerce

Viewed 444

I'm trying to hide only one of the two variations of a product in WooCommerce for visitors that are not logged in. The ID of the variation is 139. I don't know how to add the ID (or slug) to this piece of code.

    <?php // Hide WooCommerce variations for non-logged-in users
    function my_theme_hide_price_not_authorized() {
    if ( !is_user_logged_in() ) {
    // Hide variations
    add_filter( 'woocommerce_variation_is_active', 'my_theme_disable_variation', 10 , 2 );
     }
    }

    add_action('init', 'my_theme_hide_price_not_authorized');
    // Hide product variations
    function my_theme_disable_variation() {
    return false;
    }         
      

Can someone help me out?

1 Answers

Updated - To hide specific defined product variations from unlogged users, use the following:

add_filter( 'woocommerce_variation_is_visible', 'hide_specific_product_variation', 10, 4 );
function hide_specific_product_variation( $is_visible, $variation_id, $variable_product, $variation ) {
    // Here define the variation(s) ID(s) to hide
    $variations_ids_to_hide = array('139');
    
    // For unlogged user, hide defined variations
    if( ! is_user_logged_in() && in_array($variation_id, $variations_ids_to_hide ) ) {
        return false;
    }
    return $is_visible;
} 

Code goes in functions.php file of the active child theme (or active theme). It should works.

Related