首页 > 解决方案 > 从 WooCommerce 管理订单列表的自定义列中删除重复值

问题描述

我有以下代码在 WooCommerce 管理员订单列表中添加了一个自定义列

add_action( 'manage_shop_order_posts_custom_column', 'inforder_add_new_order_admin_list_column_content' );
 
function inforder_add_new_order_admin_list_column_content( $column ) {
   
    global $post;
 
if ( 'product_order' === $column ) {

        $order = wc_get_order( $post->ID );
        $items = $order->get_items();
        $count = count($items);
        $i = 1;
        foreach($items as $item) {
            if($i==$count) 
                echo $item->get_name();
            else
                echo $item->get_name() .', ';
            $i++;
        }
    }
    
    
}

但这显示了重复的值。我试图使用 array_unique()来避免这种情况,但不幸的是没有得到想要的结果。

有什么建议可以避免这种情况吗?

标签: wordpresswoocommercebackendproductorders

解决方案


您的代码包含一些错误

  • 缺少,这manage_edit-shop_order_columns是用于添加列
  • manage_shop_order_posts_custom_column不是1而是2个参数,第2个包含了$post_id所以global $post不需要使用
  • 您可以使用in_array()来检查数组中是否存在值。如果不是这种情况,我们会将这个值添加到数组中,这样我们就可以避免重复值

所以你得到:

// Add header
function filter_manage_edit_shop_order_columns( $columns ) {    
    $columns['product_order'] = __( 'Product', 'woocommerce' );

    return $columns;
}
add_filter( 'manage_edit-shop_order_columns', 'filter_manage_edit_shop_order_columns', 10, 1 );

// Display (populate the column)
function action_manage_shop_order_posts_custom_column( $column, $post_id ) {    
    // Compare
    if ( $column == 'product_order' ) {
        // Get order
        $order = wc_get_order( $post_id );
        
        // Initialize
        $names = array();

        // Is a WC_Order
        if ( is_a( $order, 'WC_Order' ) ) {
            // Get items
            $items = $order->get_items();
            
            // Loop through
            foreach ( $items as $key => $item ) {
                // Get name
                $name = $item->get_name();
                
                // NOT in array
                if ( ! in_array( $name, $names, true ) ) {
                    // Push one or more elements onto the end of array
                    array_push( $names, $name );
                }
            }
            
            // NOT empty, print result
            if ( ! empty( $names ) ) {
                // Use implode() function to join comma in the array
                $list = implode( ', ', $names );
                
                // Output
                echo $list;
            }
        }
    }
}
add_action( 'manage_shop_order_posts_custom_column' , 'action_manage_shop_order_posts_custom_column', 10, 2 );

推荐阅读