You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中通过meta_value获取WooCommerce订单

问题:如何用WordPress内置功能搜索带自定义字段的WooCommerce订单

我正在开发一个自定义WordPress插件,用来集成WooCommerce订单。插件接收一个string类型的输入,需要在WooCommerce里搜索匹配该值的订单。WooCommerce订单有个名为my_number的自定义字段,用来存储要搜索的值。

我试过用WP_Query类和get_posts函数,它们都接受args参数,但用这些WordPress内置功能查询时,完全返回不了结果!有意思的是,普通WordPress文章用同一个meta_key能正常查到结果。我甚至试过移除post_type筛选和其他字段,只保留meta_key,示例代码如下:

$args = array(
    'meta_key' => 'my_number',
);
    
$posts = get_posts( $args );
    
foreach ( $posts as $post ) {
    return ("<pre>".print_r( $post,true)."</pre>");
}

我的问题是:怎么用现有功能在WordPress中搜索WooCommerce订单?

我用MySQL语句能查到相关记录:

SELECT * FROM `wordpressTable_postmeta` WHERE meta_key = 'my_number'

截图显示该订单确实存在my_number这个自定义字段。


解决方案

问题核心在于WooCommerce订单的post_type是shop_order,且默认情况下get_posts不会包含这类自定义文章类型;另外WooCommerce订单的状态(post_status)是专属前缀wc-开头的,不是普通文章的publish状态,这两个点是导致查询无结果的关键。

方法1:使用get_posts实现精准查询

// 替换为插件接收的实际搜索字符串
$search_value = "目标搜索值";

$args = array(
    'post_type'      => 'shop_order', // 必须指定订单的专属文章类型
    'post_status'    => array('wc-pending', 'wc-processing', 'wc-completed'), // 包含需要查询的订单状态,按需增减
    'posts_per_page' => -1, // 返回所有匹配订单,如需分页可改为具体数字
    'meta_query'     => array(
        array(
            'key'     => 'my_number',
            'value'   => $search_value,
            'compare' => '=', // 精确匹配,模糊搜索可改为'LIKE'并给value加通配符
        )
    )
);

$matched_orders = get_posts( $args );

// 遍历处理匹配到的订单
foreach ( $matched_orders as $order_post ) {
    // 转换为WooCommerce订单对象,方便调用订单相关方法
    $order = wc_get_order( $order_post->ID );
    echo "<pre>".print_r( $order, true )."</pre>";
}

方法2:使用WP_Query实现查询

$search_value = "目标搜索值";

$order_query = new WP_Query( array(
    'post_type'      => 'shop_order',
    'post_status'    => array('wc-pending', 'wc-processing', 'wc-completed', 'wc-cancelled'),
    'posts_per_page' => -1,
    'meta_query'     => array(
        array(
            'key'     => 'my_number',
            'value'   => $search_value,
            'compare' => '=',
        )
    )
) );

if ( $order_query->have_posts() ) {
    while ( $order_query->have_posts() ) {
        $order_query->the_post();
        $order = wc_get_order( get_the_ID() );
        echo "<pre>".print_r( $order, true )."</pre>";
    }
    wp_reset_postdata(); // 重置查询,避免影响后续全局变量
}

关键注意事项

  • 必须指定post_type为shop_order,这是WooCommerce订单的默认文章类型标识
  • post_status要包含你需要覆盖的订单状态,WooCommerce的订单状态均以wc-为前缀,常见状态有wc-pending、wc-processing、wc-completed、wc-cancelled等
  • 使用meta_query而非单独的meta_key,既能精准匹配字段值,也能避免和普通文章的同名字段混淆
  • 若需要模糊搜索,将compare改为LIKE,并把value改为'%'.$search_value.'%'

内容的提问来源于stack exchange,提问作者Hakuna N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:10:43