如何只跟上日期的帖子在其他日期之间?(How to only keep posts with dat

2019-10-28 21:26发布

我有一些职位与在那里我有一个字符串格式的日期一些自定义字段,所以我环路我的职位,我将每个人作为一个日期,然后我做一些有点让他们按日期:

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);

因此,我与IDS一起安装的日期和给了我们:

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,现在我们要做的就是得到一些$开始并从$结束日期form使用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);

这给了我们:

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" }

现在我所要做的是一个简单的检查是否有这些职位都在我们的$开始和$结束之间的任何日期,并显示他们订购ASC或DESC

从字面上看是这样

if ( ( $myDate >= $start) && ( $myDate <= $end) ) {
 ...my posts...

但仍然给我们的所有帖子,无论

Answer 1:

你可以比较DateTime对象直接,因此您的代码可以写为:

$start = \DateTime::createFromFormat('j-n-Y', $_GET['start']);
$end = \DateTime::createFromFormat('j-n-Y', $_GET['end']);
foreach($posts as $post) {
    $postid = $post->ID;
    $myDate = \DateTime::createFromFormat('j-n-Y', get_post_meta($postid, 'usp-custom-80', true));
    if (($myDate >= $start) && ($myDate <= $end)) {
        $postOrdered[$postid] = (int)$myDate->format('U');
    }
    wp_reset_query();
}

请注意,所有你的帖子的日期是2019之前,所以你需要调整你的$start值看到输出的任何职位。

为了得到独一无二的日期排序列表,使用此代码后foreach循环:

$postOrdered = array_unique($postOrdered);
arsort($postOrdered);


文章来源: How to only keep posts with dates in between other dates?
标签: php wordpress