【问题标题】:Query post_meta date instead of post_date_gmt查询 post_meta 日期而不是 post_date_gmt
【发布时间】:2017-09-04 05:28:24
【问题描述】:

我将查询限制为使用 6 个月前的显示帖子,效果很好。

但我需要它基于post_meta 表中的日期,而不是“post_date_gmt”。

在我的例子中,我的 meta_keys 被称为 payment_date 并且值当然是像 31-10-2016 这样的日期。

$months_ago = 6;
$args = array(
'date_query' => array(
    array(
        'column' => 'post_date_gmt',
        'after'  => $months_ago . ' months ago',
        )
    ),
'numberposts'   => -1
);

【问题讨论】:

    标签: php arrays wordpress date strtotime


    【解决方案1】:

    在这里查看:https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

    如果您滚动示例,您会看到:

    显示自定义字段键为设定日期且自定义字段值为现在的帖子。仅显示日期未过的帖子。

    $args = array(
        'post_type'    => 'event',
        'meta_key'     => 'event_date',
        'meta_value'   => date( "Ymd" ), // change to how "event date" is stored
        'meta_compare' => '>',
    );
    $query = new WP_Query( $args );
    

    在你的情况下,你可以这样写:date( "dmY", strtotime( '6 months ago' ) )

    【讨论】:

      【解决方案2】:

      试试这个代码:

      $sixmonthagodate = date( "d-m-Y", strtotime('-6 Months') );
      
      $args = array(
          'post_type'    => 'post',
          'posts_per_page' => -1,
          'meta_key'     => 'payment_date',
          'meta_value'   => $sixmonthagodate,
          'meta_compare' => '>',
      );
      $query = new WP_Query( $args );
      

      检查您的 post_type 在您的 WordPress 网站中是否为真。

      【讨论】:

        【解决方案3】:

        首先date_querypost_date_gmt 上工作。如果你想 要从元字段查询帖子,则必须使用meta_query

        这是一个示例代码:

        $months_ago = 6;
        $args = [
            //...
            //...
            'posts_per_page' => -1, // Unlimited posts
            //...
            //...
            'meta_query' => [
                'relation' => 'AND',
                [
                    'key' => 'payment_date',
                    'value' => date('d-m-Y', strtotime($months_ago . ' months ago')), //<-- Converting date into your custom date format
                    'compare' => '>', //you can also use <=, >=, <, etc..
                    'type' => 'DATE'
                ],
            ]
        ];
        
        $query = new WP_Query($args);
        
        if ($query->have_posts()) :
            /* Start the Loop */
            while ($query->have_posts()) : $query->the_post();
        
            //you post
        
            endwhile;
        endif;
        

        上面的代码应该适合你。

        相关问题:

        希望这会有所帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多