简体   繁体   中英

Get order items from a specific product categories in Woocommerce 3

How can I get in Woocommerce, only specific order items from a certain product category?

I have searched in Woocommerce docs but I didn't find anything.

Here is my actual code:

<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

$order = wc_get_order($order_id);

if ( sizeof( $order->get_items() ) > 0 ) {

    foreach( $order->get_items() as $item ) {

        $_product =$order->get_product_from_item( $item );

        ?>

        <a href="<?php echo $_product->get_permalink() ?>"><?php echo $_product->get_title() ?></a>
        <br>

        <?php 
    }
}
?>

Any Help is really appreciated.

There are some mistakes in your code too… In the following code, you will define your product category(ies) that can be term Ids, slugs or names (array):

<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// HERE define your product category(ies) in this array (can be term Ids, slugs or names)
$categories = array('clothing')

// Get an instance of the WC_Order Object
$order = wc_get_order($order_id);

if ( sizeof( $order->get_items() ) > 0 ) {
    foreach( $order->get_items() as $item ) {
        // Just for a defined product category
        if( has_term( $categories, 'product_cat', $item->get_product_id() ) ) {
            // Get an instance of the WC_Product Object
            $_product = $item->get_product();
            ?>
            <a href="<?php echo $_product->get_permalink() ?>"><?php echo $item->get_name() ?></a><br>
            <?php
        }
    }
}
?>

Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM