根据类别名称woocommerce检查购物车中的产品?

时间:2014-03-22 00:35:13

标签: php woocommerce categories cart

如果某个类别的产品在我的购物车中,我试图触发一条echo声明,这是我的代码:

<?php
//Check to see if user has product in cart
global $woocommerce;

//flag no book in cart
$item_in_cart = false;

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
        $terms = get_the_terms( $_product->id, 'product_cat' );

            foreach ($terms as $term) {
                $_categoryid = $term->term_id;
            }

    if ( $_categoryid == 'name_of_category' ) {
        //book is in cart!
        $item_in_cart = true;

    }
}

if ($item_in_cart === true) {echo 'YES';}
else {echo 'Nope!';}

?>

知道我做错了什么?我确实有'name_of_category&#39;在我的购物车中的产品,我喜欢很好的回应!

谢谢!

2 个答案:

答案 0 :(得分:13)

按照Barrell的建议编辑我的代码并回应&#39;宾果&#39;!

像魅力一样,这里是代码:

    function check_product_in_cart() {
        //Check to see if user has product in cart
        global $woocommerce;

        //assigns a default negative value
        //  categories targeted 17, 18, 19

        $product_in_cart = false;

        // start of the loop that fetches the cart items

        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            $terms = get_the_terms( $_product->id, 'product_cat' );

            // second level loop search, in case some items have several categories
            foreach ($terms as $term) {
                $_categoryid = $term->term_id;
                if (( $_categoryid === 17 ) || ( $_categoryid === 18 ) || ( $_categoryid === 19 )) {
                    //category is in cart!
                    $product_in_cart = true;
                }
            }
        }

        return $product_in_cart;
   }

希望能帮助别人!

答案 1 :(得分:1)

@pillaume和其他帮助过的人 - 感谢您发布此内容对我有帮助。一旦我开始测试,我意识到代码对我的所有产品都不起作用。在我的情况下,某些产品具有子类别的类别,这阻止了代码在所有产品上获取相关类别。我稍微修改了你的代码以创建一个数组,它似乎运行良好:

function check_product_in_cart() {
    //Check to see if user has product in cart
    global $woocommerce;

    // start of the loop that fetches the cart items

    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];
        $terms = get_the_terms( $_product->id, 'product_cat' );

        // second level loop search, in case some items have several categories
        // this is where I started editing Guillaume's code

        $cat_ids = array();

        foreach ($terms as $term) {
            $cat_ids[] = $term->term_id;
        }

        if(in_array(434, (array)$cat_ids) || in_array(435, (array)$cat_ids)) {

          //category is in cart!
           $product_in_cart = true;
        }
    }

    return $product_in_cart;
}