I have some posts with some custom fields where I have a date in a string format, so I loop my posts and I convert each of them as a Date, then I do some bit to have them in order by date:
foreach($posts as $post) {
$postid = $post->ID;
$myDate = \DateTime::createFromFormat('j-n-Y', get_post_meta($postid, 'usp-custom-80', true));
$postOrdered[$postid] = \DateTime::createFromFormat('j-n-Y', get_post_meta($postid, 'usp-custom-80', true));
wp_reset_query();
}
arsort($postOrdered);
var_export($postOrdered);
So I am attaching the date together with the ids and that gives us:
array ( 128288 => DateTime::__set_state(array( 'date' => '2017-08-20 20:36:02.000000', 'timezone_type' => 3, 'timezone' => 'UTC', )), 128166 => DateTime::__set_state(array( 'date' => '2017-08-17 20:36:02.000000', 'timezone_type' => 3, 'timezone' => 'UTC', )), 128308 =>
DateTime::__set_state(array( 'date' => '2017-08-05 20:36:02.000000', DateTime::__set_state(array( 'date' => '2000-03-20 20:36:02.000000',
DateTime::__set_state(array( 'date' => '1978-05-11 20:36:02.000000', 'timezone_type' => 3, 'timezone' => 'UTC', )), 128295 =>
DateTime::__set_state(array( 'date' => '1978-04-10 20:36:02.000000', 'timezone_type' => 3, 'timezone' => 'UTC', )), 128337 =>
DateTime::__set_state(array( 'date' => '1978-03-16 20:36:02.000000', 'timezone_type' => 3, 'timezone' => 'UTC', )), 128315 => DateTime::__set_state(array( 'date' => '1976-08-10 20:36:02.000000', 'timezone_type' => 3, 'timezone' => 'UTC', )), 128290 => DateTime::__set_state(array( 'date' => '1970-04-12 20:36:02.000000', 'timezone_type' => 3, 'timezone' => 'UTC', )), )
OK now what we do is GET some $start and $end dates from a form
using GET
$start = $_GET['start'];
$end = $_GET['end'];
$start = \DateTime::createFromFormat('j-n-Y', $start);
$end = \DateTime::createFromFormat('j-n-Y', $end);
var_dump($start);
var_dump($end);
And that gives us:
object(DateTime)#8267 (3) { ["date"]=> string(26) "2019-02-01 20:51:56.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
object(DateTime)#7974 (3) { ["date"]=> string(26) "2019-02-05 20:51:56.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
Now what i am trying to do is a simple check if any of those posts have any date in between our $start and $end and display them order ASC or DESC
Literally something like
if ( ( $myDate >= $start) && ( $myDate <= $end) ) {
...my posts...
But that still gives us all posts regardless
You can just compare
DateTime
objects directly, so your code can be written as:Note that all the dates on your posts are before 2019, so you will need to adjust your
$start
value to see any posts in the output.To get a sorted list of unique dates, use this code after the
foreach
loop: