WooCommerce 避免将未登录用户添加到购物车

Ans*_*que 1 php wordpress product cart woocommerce

在我的 WooCommerce 商店中,当客户未登录时,我想避免他添加到购物车并要求他登录或注册帐户\xe2\x80\xa6

\n\n

是否可以?

\n

Loi*_*tec 6

更新- 您可以使用这两个小代码片段,这将:

\n
    \n
  • 替换商店页面和档案页面中的添加到购物车按钮/链接(对于未登录的用户)。
  • \n
  • 避免未登录的客户添加到购物车并显示自定义消息。
  • \n
\n

这是代码:

\n
// Replacing add-to-cart button in shop pages and archives pages (forn non logged in users)\nadd_filter( 'woocommerce_loop_add_to_cart_link', 'conditionally_change_loop_add_to_cart_link', 10, 2 );\nfunction conditionally_change_loop_add_to_cart_link( $html, $product ) {\n    if ( ! is_user_logged_in() ) {\n        $link = get_permalink($product_id);\n        $button_text = __( "View product", "woocommerce" );\n        $html = '<a href="'.$link.'" class="button alt add_to_cart_button">'.$button_text.'</a>';\n    }\n    return $html;\n}\n\n// Avoid add to cart for non logged user (or not registered)\nadd_filter( 'woocommerce_add_to_cart_validation', 'logged_in_customers_validation', 10, 3 );\nfunction logged_in_customers_validation( $passed, $product_id, $quantity) {\n    if( ! is_user_logged_in() ) {\n        $passed = false;\n\n        // Displaying a custom message\n        $message = __("You need to be logged in to be able adding to cart\xe2\x80\xa6", "woocommerce");\n        $button_link = get_permalink( get_option('woocommerce_myaccount_page_id') );\n        $button_text = __("Login or register", "woocommerce");\n        $message .= ' <a href="'.$button_link.'" class="login-register button" style="float:right;">'.$button_text.'</a>';\n\n        wc_add_notice( $message, 'error' );\n    }\n    return $passed;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。

\n

经过测试的广告效果。

\n