For non logged in users I use the php snippet below. Visitors see a "Where to buy" button and a "Ask a demo" button instead of the Woocommerce Add to cart button. Logged in users / customers with a specific role gets the "Add to cart button" instead of the 2 buttons for not logged in customers. There is also a viewonly role who has a login and can download materials but don't have an Add to cart button on single product pages. However with the code below the viewonly users can still see the regular Add to cart button. Any idea how i can fix this?
add_action( 'init', 'disable_add_to_cart' );
function disable_add_to_cart() {
if ( !is_user_logged_in() OR $user_role == 'viewonly' ) {
add_filter( 'woocommerce_is_purchasable', '__return_false');
}
function hide_price( $price ) {
if ( !is_user_logged_in() ) {
$price = '';
$user_role = 'viewonly';
}
return $price;
}
add_filter( 'woocommerce_get_price_html', 'hide_price' );
add_filter( 'woocommerce_cart_item_price', 'hide_price' );
add_filter( 'woocommerce_cart_item_subtotal', 'hide_price' );
add_filter( 'woocommerce_order_formatted_line_subtotal', 'hide_price' );
add_filter( 'woocommerce_cart_subtotal', 'hide_price' );
add_filter( 'woocommerce_cart_totals_order_total_html', 'hide_price' );
}
add_action( 'init', 'hide_price_add_cart_not_logged_in' );
function print_login_to_see() {
echo '<div class="var-prod-container"><a class="btn-where-to-buy" href="/where-to-buy">' . __('Where to buy', 'company') . '</a>';
echo '<a class="btn-ask-a-demo" href="/#uagb-tabs__tab1">' . __('Ask a demo', 'company') . '</a>';
echo '</div>';
}
function hide_price_add_cart_not_logged_in() {
if ( ! is_user_logged_in() ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
add_action( 'woocommerce_single_product_summary', 'print_login_to_see', 31 );
}
}```