使用短码抓取档案列表,按年份分开

时间:2014-07-02 作者:Jon

这是我修改的代码,用于显示我发布新闻的每个月的存档列表。当然,每个月都会链接到当月的档案。然后,我可以在任何我喜欢的地方包含快捷码。

function my_archives($params, $content = null) {

extract(shortcode_atts(array(
\'type\' => \'style1\'
), $params));

ob_start();
?>

<?php wp_get_archives( array( \'type\' => \'monthly\' ) ); ?>     

<?php return ob_get_clean();
}
add_shortcode(\'archives\',\'my_archives\');
然而,我无法通过阅读wp\\u get\\u归档页面来理解(http://codex.wordpress.org/Function_Reference/wp_get_archives) 如何组织月份列表,例如,以年为标题。现在,上面的代码输出如下:

<li>June 2014</li>
<li>May 2014</li>
<li>April 2014</li>
etc. etc. etc. for every year and month (my website has been up for 11 years, so that\'s over 100 links in one blob of a list).
我想知道是否有可能将列表改成这样:

<b><u>2014</u></b><ul>
<li>June 2014</li>
<li>May 2014</li>
etc.</ul>
<b><u>2013</u></b><ul>
<li>December 2014</li>
<li>November 2014</li>
etc.</ul>
谢谢大家!

2 个回复
最合适的回答,由SO网友:jocken 整理而成

我找到了这个答案:http://www.stemlegal.com/strategyblog/2011/wordpress-wednesdays-better-archive-lists-in-wordpress/

最终的代码如下所示:

function getarchives_filter($where, $args) {
    if (isset($args[\'year\'])) {
    $where .= \' AND YEAR(post_date) = \' . intval($args[\'year\']); }
    return $where;
}
add_filter(\'getarchives_where\', \'getarchives_filter\', 10, 2);

function my_archives($params, $content = null) {

    extract(shortcode_atts(array(
    \'type\' => \'style1\'
    ), $params));

    $currentyear = date(\'Y\');
    $years = range(\'2012\',$currentyear);
    foreach($years as $year){
        $archive = wp_get_archives( array( \'type\' => \'monthly\',\'echo\' => 0 ,\'year\' => $year) );
        if(!empty($archive)){
            echo \'<ul>\';
            echo \'<li>\'.$year.\'</li>\';
            echo $archive;
            echo \'</ul>\';
        }
    }

}
add_shortcode(\'archives\',\'my_archives\');

SO网友:deflime

这将输出月份和年份标题。11年已经很多了,过去我添加了一个简单的jQuery.slideToggle(), 如果用户点击某一年,则会得到该年的月份列表。只是一个建议。

  <?php
    $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = \'publish\' AND post_type = \'post\' ORDER BY post_date DESC");
    foreach($years as $year) {
    ?>

      <a class="year" href="<?php echo get_year_link($year); ?>"><?php echo $year; ?></a>
        <?php   $months = $wpdb->get_col("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_status = \'publish\' AND post_type = \'post\' AND YEAR(post_date) = \'".$year."\' ORDER BY post_date DESC");
            foreach($months as $month) {
        ?>
          <a href="<?php echo get_month_link($year, $month); ?>"><?php echo date( \'F\', mktime(0, 0, 0, $month) );?></a>
        <?php } ?>

  <?php } ?>

结束