【问题标题】:Display orders items names excluding a product category in WooCommerce在 WooCommerce 中显示不包括产品类别的订单项目名称
【发布时间】:2021-06-08 02:50:58
【问题描述】:

使用 WooCommerce,我在下面的代码中遇到了问题:我尝试从循环中跳过特定类别。产品已被跳过,但一些剩余产品多次显示:

foreach ( $order->get_items() as $item_id => $item ) {
    $product_id = $item->get_product_id();
    $terms = get_the_terms( $product_id, 'product_cat' );

    foreach ($terms as $term) {
        if ($product_cat_id != 38355) { //category id
            echo $name = $item->get_name().'<br>';
        }
    }
}

如何避免此循环中的项目名称重复?

【问题讨论】:

    标签: php wordpress woocommerce orders taxonomy-terms


    【解决方案1】:

    变量$product_cat_id 未在您的代码中定义,因此您的 if 语句始终为真。

    要检查订单商品中的产品类别,请改用conditional function has_term()。这将避免产品名称多次显示,并且属于 38355 类别 ID 的项目将被排除。

    这是您重新访问的简化代码版本:

    $item_names = array(); // Initializing
    
    foreach ( $order->get_items() as $item ) {
        // Excluding items from a product category term ID
        if ( ! has_term( 38355, 'product_cat', $item->get_product_id() ) ) {
            $item_names[] = $item->get_name();
        }
    }
    // Output 
    echo implode( '<br>', $item_names );
    

    现在应该可以正常工作了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2022-01-23
      • 2015-07-16
      • 2020-12-03
      • 2019-08-29
      • 2019-07-21
      相关资源
      最近更新 更多