WordPress:按年份分组显示归档链接

3

我目前在侧边栏中使用wp_get_archives('type=monthly')来显示存档链接。这是输出结果:

<ul>
    <li><a href='http://example.com/2011/08/'>August 2011</a></li>
    <li><a href='http://recently.se/2011/07/'>July 2011</a></li>
    <li><a href='http://recently.se/2010/12/'>December 2010</a></li>
</ul>

是否可以按年份对月份进行分组呢?类似于这样的:

<ul>
    <h2>2011</h2>
    <li><a href='http://example.com/2011/08/'>August 2011</a></li>
    <li><a href='http://recently.se/2011/07/'>July 2011</a></li>

    <h2>2010</h2>
    <li><a href='http://recently.se/2010/12/'>December 2010</a></li>
</ul>
1个回答

5
这是我实现它的方法,虽然我相信有更好的方法。我将这些函数添加到我的主题的functions.php文件中:
function twentyeleven_get_archives_callback($item, $index, $currYear) {
    global $wp_locale;

    if ( $item['year'] == $currYear ) {
        $url = get_month_link( $item['year'], $item['month'] );
        // translators: 1: month name, 2: 4-digit year
        $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($item['month']), $item['year']);
        echo get_archives_link($url, $text);
    }
}

function twentyeleven_get_archives() {
    global $wpdb;

    $query = "SELECT YEAR(post_date) AS `year` FROM $wpdb->posts WHERE `post_type` = 'post' AND `post_status` = 'publish' GROUP BY `year` ORDER BY `year` DESC";
    $arcresults = $wpdb->get_results($query);
    $years = array();

    if ($arcresults) {
        foreach ( (array)$arcresults as $arcresult ) {
            array_push($years, $arcresult->year);
        }
    }

    $query = "SELECT YEAR(post_date) as `year`, MONTH(post_date) as `month` FROM $wpdb->posts WHERE `post_type` = 'post' AND `post_status` = 'publish' GROUP BY `year`, `month` ORDER BY `year` DESC, `month` ASC";
    $arcresults = $wpdb->get_results($query, ARRAY_A);
    $months = array();

    if ( $arcresults ) {
        foreach ($years as $year) {
                    //My Display
            //echo "\t<li>\n\t\t<a href=\"#\">$year</a>\n\t\t<ul>\n";
            //array_walk($arcresults, "twentyeleven_get_archives_callback", $year);
            //echo "\t\t</ul>\n\t</li>\n";

                    //Your Display
            echo "\t<h2>$year</h2>\n\t<ul>\n";
            array_walk($arcresults, "twentyeleven_get_archives_callback", $year);
            echo "\t</ul>\n";
        }
    }
}

您可以在主题中使用以下方式调用此函数,而不是使用wp_get_archives()

<ul>
<?php twentyeleven_get_archives(); ?>
</ul>

函数名可以随意设置,不过最好的做法是以主题名称为前缀(例如,twentyeleven_)。

我参考了wp-includes/general-template.php中的wp_get_archives()get_archives_link()函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接