Home / Disable / Hide Price & Add to Cart for Non Logged in Users for Specific Products
Duplicate Snippet

Embed Snippet on Your Site

Hide Price & Add to Cart for Non Logged in Users for Specific Products

This code snippet allows you to hide the price and 'Add to Cart' button for users who are not logged in. You can specify which products you want to set as non-purchasable for non-logged-in users by defining their product IDs in this line of code:

$not_purchasable_products = array( 23, 22 ); // Replace with Products ID you want to set as non purchasable items for non logged in user.

To find the product ID, simply go to your 'Products' section and hover over the product you need the ID for. The product ID number will be displayed, as shown in this screenshot: https://snipboard.io/LDRTbm.jpg

Code Preview
php
<?php
/**
 * Hide Price & Add to Cart for Non Logged in Users for Specific Products
 */
function is_non_purchasable_products_for_visitors( $product ) {
    $not_purchasable_products = array( 23, 22 ); // Replace with Products ID you want to set as non purchasable items for non logged in user
    if ( ! is_user_logged_in() && ( in_array( $product->get_id(), $not_purchasable_products ) ) ) { 
        return true;
    } else {
        return false;
    }
}
function wws_set_not_purchasable_not_logged_in( $is_purchasable, $product ) {
    if ( is_non_purchasable_products_for_visitors( $product ) ) { 
        $is_purchasable = false;
    }
    return $is_purchasable;
}
function wws_hide_price_not_logged_in( $price_html, $product ) {
    if ( is_non_purchasable_products_for_visitors( $product ) ) { 
        $price_html = '<div><a href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '">' . __( 'Login with wholesale account to see prices', 'wws' ) . '</a></div>';
    }
    return $price_html;
}
function wws_hide_addcart_not_logged_in( $add_to_cart, $product, $args ) {
    if ( is_non_purchasable_products_for_visitors( $product ) ) { 
        $add_to_cart = '';
    }
    return $add_to_cart;
}
add_filter( 'woocommerce_is_purchasable', 'wws_set_not_purchasable_not_logged_in', 10, 2 );
add_filter( 'woocommerce_get_price_html', 'wws_hide_price_not_logged_in', 10, 2 );
add_filter( 'woocommerce_loop_add_to_cart_link', 'wws_hide_addcart_not_logged_in', 10, 3 );

Comments

Add a Comment