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

如何按date_modified查询WooCommerce产品?求未今日更新产品查询方法

正确查询WooCommerce今日未更新产品的方案

原代码问题分析

  • 使用NOT LIKE匹配日期字符串的方式不可靠:date_modified存储的是完整日期时间格式(如2022-11-17 14:30:00),部分匹配易出现误判,无法准确覆盖今日所有时间范围。
  • 未指定type为DATETIME,数据库无法正确解析日期时间进行比较。

方案一:使用OR关系筛选非今日时间范围

$limit = 400;
// 获取适配WordPress时区的今日起止时间
$today_start = date('Y-m-d 00:00:00', current_time('timestamp'));
$today_end = date('Y-m-d 23:59:59', current_time('timestamp'));

$products_ids = get_posts(array(
    'post_type'      => array('product', 'product_variation'),
    'numberposts'    => $limit,
    'post_status'    => 'publish',
    'fields'         => 'ids',
    'meta_query'     => array(
        'relation' => 'OR',
        // 筛选修改时间早于今日0点的产品
        array(
            'key'     => 'date_modified',
            'value'   => $today_start,
            'compare' => '<',
            'type'    => 'DATETIME'
        ),
        // 筛选修改时间晚于今日23:59:59的产品
        array(
            'key'     => 'date_modified',
            'value'   => $today_end,
            'compare' => '>',
            'type'    => 'DATETIME'
        )
    )
));

print_r($products_ids);

方案二:使用NOT BETWEEN简化查询

$limit = 400;
$today_start = date('Y-m-d 00:00:00', current_time('timestamp'));
$today_end = date('Y-m-d 23:59:59', current_time('timestamp'));

$products_ids = get_posts(array(
    'post_type'      => array('product', 'product_variation'),
    'numberposts'    => $limit,
    'post_status'    => 'publish',
    'fields'         => 'ids',
    'meta_query'     => array(
        array(
            'key'     => 'date_modified',
            'value'   => array($today_start, $today_end),
            'compare' => 'NOT BETWEEN',
            'type'    => 'DATETIME'
        )
    )
));

print_r($products_ids);

关键说明

  • 使用current_time('timestamp')确保时间适配WordPress后台设置的时区,避免时区差异导致的查询偏差。
  • 指定type => 'DATETIME'让数据库以日期时间类型解析字段值,保证比较逻辑的准确性。
  • 两种方案效果一致,方案二更简洁,方案一逻辑更直观,可根据习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:15:33