admin管理员组

文章数量:1122846

An administrator wants to make posts for a future date but not visible for visitors. The posts come from a custom WP_Query inside my plugin so the basical WP behaviour does not work in this case.

I tried this :

$args = array(
    'post_type' => "my-post-type",
    'date_query'          => array(
        'before' => 'today',
        'inclusive' => true
    )
);

$args['posts_per_page'] = -1;
...   
return new \WP_Query( $args );

But if I wrote a post with the post_date is today, it does not appear. How can I include the post with post_date before today and today (1 second before now) ?

An administrator wants to make posts for a future date but not visible for visitors. The posts come from a custom WP_Query inside my plugin so the basical WP behaviour does not work in this case.

I tried this :

$args = array(
    'post_type' => "my-post-type",
    'date_query'          => array(
        'before' => 'today',
        'inclusive' => true
    )
);

$args['posts_per_page'] = -1;
...   
return new \WP_Query( $args );

But if I wrote a post with the post_date is today, it does not appear. How can I include the post with post_date before today and today (1 second before now) ?

Share Improve this question asked Sep 5, 2019 at 15:48 J.BizMaiJ.BizMai 9002 gold badges10 silver badges30 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 0

You need to pass a strtotime() compatible string or an array instead of 'today'.

You have several options...

  1. You could change 'today' to 'now'. This will use the current time not midnight last night.
  2. You could change 'today' to 'today + 1 day'. This will be the end of today. Not exactly what you are asking for but worth mentioning.
  3. You could generate it with PHP like date('d-m-Y H:i:s'). This is unnecessary extra work since it will need to be parsed just like 'now'.

Of all of these options, 1 is the simplest and most comprehendable.

Documentation

https://developer.wordpress.org/reference/classes/wp_query/#date-parameters

https://www.php.net/strtotime

it looks like user D. Morell already gave you a good answer, but based on your story you can simplify this whole process pretty easily by just making the publish date of those future posts the future date so that they are not available on the site until those dates.

you can modify your date_query to include posts with a date up to the current time

$args = array(
    'post_type' => "my-post-type",
    'date_query' => array(
        'before' => current_time('mysql'), // Include posts before current time
        'inclusive' => true
    )
);

$args['posts_per_page'] = -1;
...
return new \WP_Query($args);

本文标签: wp queryHow to get only present and past posts with postdate