简体   繁体   中英

Woocommerce Problem disabling the Add to Cart button for unregistered users

I use the following code in the functions.php file in the child theme:

add_filter( 'woocommerce_variable_sale_price_html', 'update_price_html', 10, 2 );

add_filter( 'woocommerce_variable_price_html', 'update_price_html', 10, 2 );

add_filter( 'woocommerce_get_price_html','update_price_html', 9999, 2 );

function update_price_html( $html, $product ) {

     if(!is_user_logged_in()) {  // Si el usuario no está logueado

        add_filter( 'woocommerce_is_purchasable', '__return_false');

        $html = "Necesita registrarse para ver precios";

        return $html;

    } else {

        return $html;

    }

}

This code works perfectly fine to hide prices from unregistered users. But in the case of hiding the “Add to cart” button, it presents the problem that it does not hide it in the first product in the category list, although it does for all other products.

This problem occurs for any product category and / or subcategory, change the “Add to cart” button for the “Read more” button in all the products in the list except the first one.

Using this code in your function.php file can hide the add to cart button for unregistered users and direct them to login to view the prices to buy. It also hides the add to cart button in shop page , product category page and product detail page . Enjoy!

/**
     * @snippet       Hide Price & Add to Cart for Logged Out Users
     * @author        reikyal
     * @testedwith    WooCommerce 5.7 and above
     */
      
    add_filter( 'woocommerce_get_price_html', 'hide_price_addcart_not_logged_in', 9999, 2 );
     
    function hide_price_addcart_not_logged_in( $price, $product ) {
       if ( ! is_user_logged_in() ) { 
          $price = '<div><a href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '">' . __( 'Login to see prices', 'add_to_cart' ) . '</a></div>';
          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 );
       }
       return $price;
    }

To remove the add to cart button from the archive pages, you can use callback function woocommerce_template_loop_add_to_cart .

function so69379738_remove_woocommerce_hooks() {
    if(!is_user_logged_in()) {
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    }
}
add_action('wp_head', 'so69379738_remove_woocommerce_hooks');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM