在我的网站上(使用Woocommerce 3.2.6),我想仅为登录用户隐藏“添加到购物车”按钮。
我有这段代码:
add_action('init', 'hide_price_add_cart_logged_in');
function hide_price_add_cart_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 );
}
}
编辑:有人建议我使用它:
add_action('init', 'hide_price_add_cart_logged_in');
function hide_price_add_cart_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 );
return WooCommerce::instance();
}
}
但那确实不工作......
我已将此代码插入到我的主题的functions.php文件中,但它似乎没有做任何更改。检查某些产品时,我仍然看到添加到购物车按钮。
如何删除该按钮?我的功能在哪里出错?
答案 0 :(得分:3)
你应该试试这个:
add_action( 'woocommerce_after_shop_loop_item', 'remove_loop_add_to_cart_button', 1 );
function remove_loop_add_to_cart_button() {
// Only for logged in users
if( ! is_user_logged_in() ) return;
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
}
add_action( 'woocommerce_single_product_summary', 'remove_add_to_cart_button', 1 );
function remove_add_to_cart_button() {
// Only for logged in users
if( ! is_user_logged_in() ) return;
global $product;
// For variable product types (keeping attribute select fields)
if( $product->is_type( 'variable' ) ) {
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
}
// For all other product types
else {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}
}
代码进入活动子主题(或活动主题)的function.php文件。
经过测试和工作
您可以使用链接到产品的按钮替换它,而不是隐藏存档页面(如商店)上的添加到购物车按钮。所以代码将改为:
// Replacing the button add to cart by a link to the product in Shop and archives pages
add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product ) {
// Only for logged in users
if( ! is_user_logged_in() ) return;
$button_text = __( "View product", "woocommerce" );
$button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
return $button;
}
add_action( 'woocommerce_single_product_summary', 'remove_add_to_cart_button', 1 );
function remove_add_to_cart_button() {
// Only for logged in users
if( ! is_user_logged_in() ) return;
global $product;
// For variable product types (keeping attribute select fields)
if( $product->is_type( 'variable' ) ) {
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
}
// For all other product types
else {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );;
}
}
代码进入活动子主题(或活动主题)的function.php文件。
经过测试和工作