有如下图所示情况,需要把文章以年份和月份的形式排列出来。(project:sunwood)

那么我们可以通过将每篇文章的发布年份和月份先挑出来形成一个结构型数组,然后再进行内容的输出。

$years = array();
$works_args = array(
    'post_type' => 'business',
    'tax_query' => array(
        array(
            'taxonomy' => 'business_tax',
            'field' => 'term_id',
            'terms' => get_queried_object_id(),
        ),
    ),
    'posts_per_page' => -1,
);
$works_query = new WP_Query($works_args);
if ($works_query->have_posts()) {
    while ($works_query->have_posts()) {
        $works_query->the_post();
        $year = get_the_date('Y');
        $m = get_the_date('m');
        if (!isset($years[$year])) {
            $years[$year] = array();
            if (!isset($years[$year][$m])) {
                $years[$year][$m] = array();
            }
        }
        $years[$year][$m][] = array('title' => get_the_title(), 'permalink' => get_the_permalink());
    }
}