【问题标题】:List Category and Sub Category Of Product Purchased Separately on WooCommerce Order Page在 WooCommerce 订单页面上列出单独购买的产品的类别和子类别
【发布时间】:2022-01-09 16:42:21
【问题描述】:

我要求在 WooCommerce 中购买的产品的类别和子类别在 WooCommerce 订单页面上作为数据属性单独回显。以下 $terms 会返回产品购买的类别和子类别列表。

有没有办法分别列出通过 WooCommerce 购买的产品的主类别和子类别


// Display order items product categories and its id 
add_action( 'woocommerce_order_item_meta_end', 'display_custom_data_in_emails', 10, 4 );
function display_custom_data_in_emails( $item_id, $item, $order, $bool ) {
    // Get the product categories for this item
    $terms = wp_get_post_terms( $item->get_product_id(), 'product_cat', array( 'fields' => 'names' ) );
    $term_ids = wp_get_post_terms( $item->get_product_id(), 'product_cat', array( 'fields' => 'ids' ) );
    echo "<div data-category=" . implode(', ', $terms) . "></div>";
    echo "<div data-catid=" . implode(', ', $term_ids) . "></div>";
    
}

【问题讨论】:

    标签: wordpress woocommerce hook-woocommerce


    【解决方案1】:

    您需要获取与该产品相关的所有条款。然后你可以迭代术语循环并检查parent == 0,这样你就只会得到父术语。试试下面的代码。

    // Display order items product categories and its id 
    add_action( 'woocommerce_order_item_meta_end', 'display_custom_data_in_emails', 10, 4 );
    function display_custom_data_in_emails( $item_id, $item, $order, $bool ) {
        // Get the product categories for this item
        $terms = wp_get_post_terms( $item->get_product_id(), 'product_cat' );
    
        $parent_categories = $child_categories = $parent_categories_ids = $child_categories_ids = array();
    
        foreach( $terms as $category ) {
            if( $category->parent == 0 ) {
                $parent_categories[] = $category->name;
                $parent_categories_ids[] = $category->term_id;
            }else{
                $child_categories[] = $category->name;
                $child_categories_ids[] = $category->term_id;
            }
        }
    
        echo '<div data-category="'.implode(', ', $parent_categories).'">Parent category names: '.implode(', ', $parent_categories).'</div>';
        echo '<div data-catid="'.implode(', ', $parent_categories_ids).'">Child category names: '.implode(', ', $parent_categories_ids).'</div>';    
    
        echo '<div data-category="'.implode(', ', $child_categories).'">Parent category ids: '.implode(', ', $child_categories).'</div>';
        echo '<div data-catid="'.implode(', ', $child_categories_ids).'">Child category ids: '.implode(', ', $child_categories_ids).'</div>';    
    }
    

    经过测试且有效

    【讨论】:

    • 它的工作原理是将子类别名称映射到父类别 ID 并将父类别 ID 映射到子类别的代码。我已经更改了我的代码。谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多