我为具有自定义字段且带有诸如22/5/2018
这样的字符串的帖子运行循环,我需要按日期对帖子进行排序,所以我这样做:
$postOrdered = array();
$queryPosts = new WP_Query(array(
'posts_per_page' => -1,
'post__in' => $postIds,
'order' => 'DESC',
'orderby' => 'DATE',
'meta_key' => 'usp-custom-80',
'type' => 'DATE',
)
);
if( $queryPosts->have_posts() ):
while ( $queryPosts->have_posts() ) : $queryPosts->the_post();
array_push($postOrdered, $post->ID);
$date = usp_get_meta(false, 'usp-custom-80');
echo $date."<br>";
endwhile;
endif;
我得到:
2-6-2015
21-12-2018
26-12-2018
18-12-2018
27-12-2018
12-11-2018
21-12-2018
7-12-2018
5-12-2018
5-12-2018
6-12-2018
19-12-2018
7-12-2018
13-12-2018
24-11-2000
25-11-2018
13-11-2018
我想通过这样做将字符串转换为日期
$postOrdered = array();
$date = usp_get_meta(false, 'usp-custom-80');
$date = DateTime::createFromFormat("d.m.Y", $date)->format("m/d/Y");
$queryPosts = new WP_Query(array(
'posts_per_page' => -1,
'post__in' => $postIds,
'order' => 'DESC',
'orderby' => $date,
'meta_key' => 'usp-custom-80',
'type' => 'DATE',
)
);
if( $queryPosts->have_posts() ):
while ( $queryPosts->have_posts() ) : $queryPosts->the_post();
array_push($postOrdered, $post->ID);
$dateOrdered = usp_get_meta(false, 'usp-custom-80');
echo $dateOrdered."<br>";
endwhile;
endif;
但是我什么也没得到
答案 0 :(得分:0)
将代码更改为如下所示:
if( $queryPosts->have_posts() ):
$dateOrdered = [];
while ( $queryPosts->have_posts() ) : $queryPosts->the_post();
array_push($postOrdered, $post->ID);
$dateOrdered[] = usp_get_meta(false, 'usp-custom-80');
//echo $dateOrdered."<br>";
endwhile;
endif;
function custom_sort_dt($a, $b) {
return strtotime($a) - strtotime($b);
}
usort($dateOrdered, "custom_sort_dt");
print_r($dateOrdered);
请参考: