簡體   English   中英

根據類別名稱woocommerce檢查購物車中的產品?

[英]Checking products in cart based on category name woocommerce?

如果某個類別的產品在我的購物車中,我試圖觸發一個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'產品,我想要一個很好的回復!

謝謝!

按照Barrell的建議編輯我的代碼並回應'賓果'!

像魅力一樣工作,這里是代碼:

    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;
   }

希望能幫助別人!

@Guillaume和其他幫助過的人 - 感謝您發布此內容對我有幫助。 一旦我開始測試,我意識到代碼不適用於我的所有產品。 在我的情況下,某些產品具有子類別的類別,這阻止了代碼在所有產品上獲取相關類別。 我稍微修改了你的代碼以創建一個數組,它似乎運行良好:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM