WooCommerce Avoid add to cart for non logged user

杀马特。学长 韩版系。学妹 提交于 2019-12-13 17:34:23

问题


In my WooCommerce shop, when a customers is not logged in I would like to avoid him adding to cart asking him to either login or register an account…

Is it possible?


回答1:


Updated - You could use this 2 little snippets of code, that will:

  • Replace add-to-cart button/link in shop pages and archives pages (for non logged in users).
  • Avoid non logged in customers adding to cart and displaying a custom message.

Here is the code:

// Replacing add-to-cart button in shop pages and archives pages (forn non logged in users)
add_filter( 'woocommerce_loop_add_to_cart_link', 'conditionally_change_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( ! is_user_logged_in() ) {
        $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;
}

// Avoid add to cart for non logged user (or not registered)
add_filter( 'woocommerce_add_to_cart_validation', 'logged_in_customers_validation', 10, 3 );
function logged_in_customers_validation( $passed, $product_id, $quantity) {
    if( ! is_user_logged_in() ) {
        $passed = false;

        // Displaying a custom message
        $message = __("You need to be logged in to be able adding to cart…", "woocommerce");
        $button_link = get_permalink( get_option('woocommerce_myaccount_page_id') );
        $button_text = __("Login or register", "woocommerce");
        $message .= ' <a href="'.$button_link.'" class="login-register button" style="float:right;">'.$button_text.'</a>';

        wc_add_notice( $message, 'error' );
    }
    return $passed;
}

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

Tested ad works.



来源:https://stackoverflow.com/questions/47246951/woocommerce-avoid-add-to-cart-for-non-logged-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!