【发布时间】:2017-01-31 08:41:37
【问题描述】:
如果他们的购物篮中没有特定的产品类别,我想阻止任何客户前进到结账处。我还想通过错误消息告诉他们他们需要添加某个产品。我找到了一些代码,但无法正常工作。我已将它作为代码 sn-p 添加到我的 Wordpress 安装中,但是即使我打开了调试,它也不起作用并且没有错误消息。这是我在 Github 中找到的代码,可能需要修改才能使其正常工作:
function sv_wc_prevent_checkout_for_category() {
// set the slug of the category for which we disallow checkout
$category = 'sibling';
// get the product category
$product_cat = get_term_by( 'slug', $category, 'product_cat' );
// sanity check to prevent fatals if the term doesn't exist
if ( is_wp_error( $product_cat ) ) {
return;
}
$category_name = '<a href="' . get_term_link( $category, 'product_cat' ) . '">' . $product_cat->name . '</a>';
// check if this category is the only thing in the cart
if ( sv_wc_is_category_alone_in_cart( $category ) ) {
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category – you must purchase a product from another category to check out.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
/**
* Checks if a cart contains exclusively products in a given category
*
* @param string $category the slug of the product category
* @return bool - true if the cart only contains the given category
*/
function sv_wc_is_category_alone_in_cart( $category ) {
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// if a product is not in our category, bail out since we know the category is not alone
if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
return false;
}
}
// if we're here, all items in the cart are in our category
return true;
}
因此,如果“兄弟”类别是购物车中唯一的商品,我希望停止结帐(带有错误消息)。我有一个“标准”类别,在客户结账之前必须在购物篮中。希望这是有道理的。
【问题讨论】:
标签: php wordpress woocommerce categories cart