WooCommerce避免为未登录的用户添加到购物车 [英] WooCommerce Avoid add to cart for non logged user
本文介绍了WooCommerce避免为未登录的用户添加到购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的WooCommerce商店中,当客户未登录时,我希望避免他加入购物车要求他登录或注册帐户...
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…
是
推荐答案
已更新-您可以使用这两个小片段代码,它们将:
Updated - You could use this 2 little snippets of code, that will:
- 替换商店页面和档案页面中的购物车按钮/链接(对于未登录的用户)。
- 避免将未登录的客户添加到购物车并显示自定义消息。
以下是代码:
// 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;
}
代码进入活动子主题(或主题)的function.php文件
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
经过测试的广告作品。
这篇关于WooCommerce避免为未登录的用户添加到购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文