下面,我修改了我先前为批发客户编写的一些代码。该代码删除了价格和“添加到购物车”按钮,并完全阻止了这些产品的购买。
add_action( 'template_redirect','hide_price_and_add_cart' );
// The first hook that is safe to get post id is template_redirect
function hide_price_and_add_cart() {
$postID = get_queried_object_id();
if ( ( is_product( $postID ) && has_term( 'sample_category','product_cat' ) ) ||
// if single product pages in the category "sample_category"
( is_product_category( 'sample_category' ) )
// or,if product category pages "sample_category"
) {
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
if ( ! in_array( 'sample_category_customer',(array) $user->roles ) ) {
remove_action( 'woocommerce_after_shop_loop_item','woocommerce_template_loop_add_to_cart',10 );
// remove 'Add to Cart' from product category page
remove_action( 'woocommerce_single_product_summary','woocommerce_template_single_add_to_cart',30 );
// remove 'Add to Cart' from single product page
remove_action( 'woocommerce_after_shop_loop_item_title','woocommerce_template_loop_price',10 );
// remove price from product category page
remove_action( 'woocommerce_single_product_summary','woocommerce_template_single_price',10 );
// remove price from single product page
add_action( 'woocommerce_single_product_summary','print_login_to_access',31 );
// Print 'Register for price' on single product page
add_action( 'woocommerce_after_shop_loop_item',11 );
// Print 'Register for price' on product category page
add_filter( 'woocommerce_is_purchasable','__return_false');
// Finally,let's just make sure the product cannot be purchased...
}
} else {
// If user is not logged in,hide everything as well
remove_action( 'woocommerce_after_shop_loop_item',10 );
remove_action( 'woocommerce_single_product_summary',30 );
remove_action( 'woocommerce_after_shop_loop_item_title',10 );
add_action( 'woocommerce_single_product_summary',31 );
add_action( 'woocommerce_after_shop_loop_item',11 );
add_filter( 'woocommerce_is_purchasable','__return_false');
}
}
}
function print_login_to_access() {
echo '<p>Register for price</p>';
}
注意-此代码仅适用于父类别“样品类别”中列出的产品。如果它们在父目录中也列出,则适用于子类别中的产品。如果您不希望它们也列在父级猫中-仅子级猫中,则需要一些代码以递归方式向下钻取并标识父级。
本文链接:https://www.f2er.com/3158761.html