Search code examples
phpwordpresswoocommerceproductcart

WooCommerce remove shopping cart by user role


In Woocommerce, I have a function that replace add to cart button by a linked button to the product in shop and archive pages:

function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
if ( ! current_user_can('customer') ) {
    $link = get_permalink($product_id);
    $button_text = __( "View product", "woocommerce" );
    $html = '<a href="'.$link.'" class="button alt add_to_cart_button">'.$button_text.'</a>';
}
return $html;
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'conditionally_change_loop_add_to_cart_link', 10, 2 );

I would like to remove the add to cart button on all pages if a user is not logged in as a customer.

Can anyone help please?


Solution

  • Instead of your actual code, try the following that will do everything everywhere and will remove add to cart button when user is not logged in:

    add_filter('woocommerce_is_purchasable', 'woocommerce_is_purchasable_filter_callback', 10, 2 );
    function woocommerce_is_purchasable_filter_callback( $purchasable, $product ) {
        if ( ! is_user_logged_in() ) 
            $purchasable = false;
    
        return $purchasable;
    }
    

    Code goes in function.php file of your active child theme (or active theme).