在 WooCommerce 订单管理页面中按订单项 SKU 或 ID 搜索

时间:2022-11-16
本文介绍了在 WooCommerce 订单管理页面中按订单项 SKU 或 ID 搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想要做的是能够在 WooCommerce 订单管理页面中按订单商品 SKU 或 ID 进行搜索.

What I am trying to do is to be able to search by order item SKU or ID in the WooCommerce Orders Admin page.

到目前为止我发现/完成的,但没有成功的是 functions.php 文件中的以下内容.

What I have found/done till now, but with no success is the following at functions.php file.

add_filter( 'woocommerce_shop_order_search_fields', 'woocommerce_shop_order_search_sku' );

function woocommerce_shop_order_search_sku( $search_fields ) {

    $args = array( 'post_type' => 'shop_order' );

    $orders = new WP_Query( $args );

    if ( $orders->have_posts() ) {
        while( $orders->have_posts() ) {
            $post = $orders->the_post();
            $order_id = get_the_ID();
            $order = new WC_Order( $order_id );
            $items = $order->get_items();
            foreach( $items as $item ) {
                $search_order_item_sku = wp_get_post_terms( $item['product_id'], 'search_sku' );
                foreach( $search_order_item_sku as $search_sku ) {
                    add_post_meta( $order_id, "_search_sku", $search_sku->sku );
                }
            }
        }
    };

    $search_fields[] = '_search_sku';

    return $search_fields;

}

我想问题在于 $search_skuadd_post_meta 所在行的值.

I suppose the issue is the value of $search_sku at the line with the add_post_meta.

我也用 get_sku()$item['sku'] 尝试过,但没有成功.

I have also tried it with get_sku(), $item['sku'] with no luck.

推荐答案

@blacksquare、@jibby、@helgatheviking 你们是男人!由于您的帮助,这是有效的代码.

@blacksquare, @jibby, @helgatheviking you are the men! This is the code that works, due to your help.

    //Search by product SKU in Admin Woocommerce Orders
add_filter( 'woocommerce_shop_order_search_fields', function ($search_fields ) {
    $posts = get_posts(array('post_type' => 'shop_order'));

    foreach ($posts as $post) {
        $order_id = $post->ID;
        $order = new WC_Order($order_id);
        $items = $order->get_items();

        foreach($items as $item) {
            $product_id = $item['product_id'];
            $search_sku = get_post_meta($product_id, "_sku", true);
            add_post_meta($order_id, "_product_sku", $search_sku);
        }
    }

    return array_merge($search_fields, array('_product_sku'));
});

这篇关于在 WooCommerce 订单管理页面中按订单项 SKU 或 ID 搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:PHP/MySQL 小规模模糊搜索 下一篇:如何生成类似于 Google 使用 PHP 和 MySQL 生成的代码段?

相关文章

最新文章