【问题标题】:Wordpress ACF query posts where datetime field is empty or older than 1 day日期时间字段为空或超过 1 天的 Wordpress ACF 查询帖子
【发布时间】:2021-05-18 06:43:30
【问题描述】:

我有一个自定义帖子类型 (affiliate_products),其中包含我每天通过 API 和 WP Cron 作业更新的价格字段。因为我的网站上有很多附属产品,所以我将它们分成 5 个批次,每分钟运行一个 cron。

为此,我使用了一个 ACF 日期时间字段 last_update,该字段在更新时使用当前日期和时间进行更新。但我的 WP 查询有问题;

我需要获得 5 个 last_update 字段为空的帖子(尚未更新的新产品)或上次更新时间超过 1 天的帖子。 (日期

但我的查询不起作用。元查询的第一部分正在工作,但是一旦我添加了 meta_query 的第二部分,就不再返回任何结果,即使仍然有很多产品的 last_update 字段为空。我的代码可能有什么问题?

我意识到我还没有任何 last_update 日期大于 1 天的产品,但它仍应返回带有空 last_update 字段的产品,对吧?

$args_products = array(
        'posts_per_page'    => 5,
        'post_type'         => 'affiliate_products',
        'meta_query'        => array(
            'relation'          => 'OR',
                array(
                    'key'       => 'last_update',
                    'compare'   => 'NOT EXISTS'
                ),
                array(
                    'key'       => 'last_update',
                    'value'     => date('Y-m-d H:i:s'),
                    'compare'   => '<',
                    'type'      => 'DATETIME'
                ),
            )
    );

    $the_product_query = new WP_Query( $args_products );

    if( $the_product_query->have_posts() ) {
        while( $the_product_query->have_posts() ) { 
            $the_product_query->the_post();
            // the update code goes here
        }
    }

【问题讨论】:

    标签: php wordpress advanced-custom-fields acfpro


    【解决方案1】:

    尝试Ymd 格式。在这里查看date-picker

    $args_products = array(
        'posts_per_page'    => 5,
        'post_type'         => 'affiliate_products',
        'meta_query'        => array(
            'relation'          => 'OR',
                array(
                    'key'       => 'last_update',
                    'compare'   => 'NOT EXISTS'
                ),
                array(
                    'key'       => 'last_update',
                    'value'     => date('Y-m-d H:i:s',strtotime('-1 day')),
                    'compare'   => '<',
                    'type'      => 'DATETIME'
                ),
            )
    );
    
    $the_product_query = new WP_Query( $args_products );
    
    if( $the_product_query->have_posts() ) {
        while( $the_product_query->have_posts() ) { 
            $the_product_query->the_post();
            // the update code goes here
        }
    }
    

    【讨论】:

    • 但是我使用的是 DateTime 字段,我不需要时间信息来确保每天(每 24 小时)更新产品吗?
    • 你检查过它是如何存储在数据库中的吗?
    • 根据 ACF 文档 (advancedcustomfields.com/resources/date-time-picker),它以 Y-m-d H:i:s 的形式存储在数据库中。
    • 您说last_update 键存在但值为空?
    • 元查询的第一部分选择last_update字段为空的产品(因此尚未自动更新的新产品)。这工作正常。我认为问题出在元查询的第二部分,即 DATETIME 值。当我注释掉元查询的其余部分并只留下这部分时,每次运行(每分钟)都会更新相同的 5 个产品,即使它们在一分钟前刚刚更新。所以查询的那部分有问题,但我不知道是什么。我遵循了 ACF 文档..
    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 2017-02-22
    • 2017-10-24
    • 1970-01-01
    • 2011-01-08
    • 2018-10-02
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多