在我的 WooCommerce 商店中,我想隐藏价格,直到客户登录为止。我有以下代码可以实现这一点:
add_action('init','hide_price');
function hide_price(){
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);
remove_action('woocommerce_single_product_summary','woocommerce_template_single_price',10);
remove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_price',10);
add_action('woocommerce_single_product_summary','print_login_to_see',31);
add_action('woocommerce_after_shop_loop_item','print_login_to_see',11);
}
}
function print_login_to_see(){
echo '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) . '">' . __('Login to see prices','theme_name') . '</a>';
}
然而,这也消除了变化下拉列表,我想保留它。
有没有直接的方法来保留变化下拉菜单,但仍然隐藏价格,直到客户登录?
谢谢
更新:
您需要将商店和档案页面与单个产品页面分开。在单个产品页面中,您将针对可变产品来添加和删除特定的挂钩函数。
最后一件事,在你的函数中
print_login_to_see()
,woocommerce_get_page_id()
已过时,它已被wc_get_page_id()
取代......
所以你的代码会这样:
// For product archives pages
add_action( 'init', 'hide_product_archives_prices' );
function hide_product_archives_prices(){
if( is_user_logged_in() ) return;
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10) ;
add_action ( 'woocommerce_after_shop_loop_item', 'print_login_to_see', 10 );
}
//
add_action( 'woocommerce_single_product_summary', 'hide_single_product_prices', 1 );
function hide_single_product_prices(){
if( is_user_logged_in() ) return;
global $product;
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
if( ! $product->is_type('variable') ){
remove_action('woocommerce_single_product_summary','woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary','print_login_to_see', 30 );
} else {
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation', 10);
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
add_action( 'woocommerce_single_variation', 'print_login_to_see', 20 );
}
}
// Display a my account link
function print_login_to_see(){
echo '<a href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '" class="button">' . __('Login to see prices','theme_name') . '</a>';
}
代码位于活动子主题(或主题)的 function.php 文件中,或者也位于任何插件文件中。
此代码在 WooCommerce 3+ 上经过测试并且有效。