Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

php - Checking products in cart based on category name woocommerce?

I'm trying to trigger an echo statement if a certain category of product is in my cart, here's my code:

<?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!';}

?>

Any idea as to what i'm doing wrong? I do have 'name_of_category' products in my cart, i'd like a nice Yes echoed!

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edited my code following Barrell's advice and echo 'Bingo'!

Works like a charm, here's the code:

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

Hope that can help someone!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...