wordpress - 从 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()来避免这种情况,但不幸的是没有得到想要的结果。
有什么建议可以避免这种情况吗?
解决方案
您的代码包含一些错误
- 缺少,这
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 );
推荐阅读
- c# - 散列或加密或两者都存储用户的密码?C# Winforms
- excel - Excel replace each char in a string contained in another list
- mysql - Spring Data JPA 只接受持久化数据的时间
- angular - 角度服务工作者 swpush.messages 响应(通知)对象未加载
- flutter - 如何解决小部件库捕获的异常?
- pandas - 通过使用 pandas 将定义的条件与输入列进行比较,在数据集中追加一个空的输出列
- google-apps-script - 使用 Google 应用脚本在 Google 表格中创建宏
- webpack - 使用 customize-cra 从 node_modules 中的 bundle.js 中删除包
- node.js - 在 mongoose 聚合中修改 $cond 的结果值?
- python - 无法为 Python 安装 Kivy