以下解决方案已经过全面测试,并且对于默认的 wordpress post 类型可以无缝运行。如果您想为具有自己的自定义字段的自定义帖子类型运行它,那么您可能会遇到一些差异。因此,请随时根据需要为您自己的自定义帖子类型进行自定义。
正如我们在this question 上讨论的那样,当您使用get_posts 时,它将返回post objects。每个post object 包含以下属性/数据:
WP_Post Object
(
[ID] =>
[post_author] =>
[post_date] =>
[post_date_gmt] =>
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] =>
[comment_status] =>
[ping_status] =>
[post_password] =>
[post_name] =>
[to_ping] =>
[pinged] =>
[post_modified] =>
[post_modified_gmt] =>
[post_content_filtered] =>
[post_parent] =>
[guid] =>
[menu_order] =>
[post_type] =>
[post_mime_type] =>
[comment_count] =>
[filter] =>
)
例如,如果您需要帖子的title、content、author、exerpt,那么您可以创建一个多维数组并使用array_push 函数来创建您的自定义数组,如下所示:
$posts = get_posts(array(
'post_type' => 'history', // Since 'history' is a custom post type, I tested it on 'post'
//'post_type' => 'post'
'posts_per_page' => -1,
'orderby' => 'date'
));
// You could see the number of posts for your query
echo "Number of posts found: ". count($posts) . "<br>";
$your_custom_array_yearly = array();
foreach ($posts as $post) {
setup_postdata($post);
$time = strtotime($post->post_date);
$year = date('Y', $time);
$mon = date('F', $time);
if (!($your_custom_array_yearly[$year][$mon])) {
$your_custom_array_yearly[$year][$mon] = array();
array_push(
$your_custom_array_yearly[$year][$mon],
[
'title' => $post->post_title,
'excerpt' => $post->post_excerpt,
'author' => $post->post_author,
'content' => $post->post_content,
]
);
} else {
array_push(
$your_custom_array_yearly[$year][$mon],
[
'title' => $post->post_title,
'excerpt' => $post->post_excerpt,
'author' => $post->post_author,
'content' => $post->post_content,
]
);
};
}
wp_reset_postdata();
为了调试/调查数组,你可以使用这个:
echo "<pre>";
print_r($your_custom_array_yearly);
echo "</pre>";
既然您有自己的自定义数组,那么您可以循环遍历它并输出您的数据:
foreach ((array)$your_custom_array_yearly as $yearly => $yvalue) {
echo $yearly . ": <br>";
echo "<ul>";
foreach ($yvalue as $monthly => $mvalue) {
echo "<li>" . $monthly . ": </li><ul>";
foreach ($mvalue as $monthly_k => $monthly_v) {
foreach ($monthly_v as $post_title_k => $post_title_v) {
echo "<li>" . $post_title_k . ": " . $post_title_v . "</li></ul>";
}
}
}
echo "</ul>";
}
以上代码会输出如下结果:
2021:
January:
1.Title: Post Title
1.Excerpt: Post excerpt
1.Author: Post author
1.Content: Post content
2.Title: Post Title
2.Excerpt: Post excerpt
2.Author: Post author
2.Content: Post content
March:
3.Title: Post Title
3.Excerpt: Post excerpt
3.Author: Post author
3.Content: Post content
2020:
May:
4.Title: Post Title
4.Excerpt: Post excerpt
4.Author: Post author
4.Content: Post content