代码实现WordPress文章归档页面

WordPress的文章归档还是很有必要的,特别是文章多了之后,用归档可以很方便的找到想要找的文章,网上有很多的插件可以实现这个功能,不过我们喜欢折腾,那么就不用插件,而是使用代码来实现。

如果在配合Jquery的话,可以实现非常棒的效果。

下面我就说下简单的操作方法。

1、把下面的 archives_list_SHe 函数代码添加到主题的 functions.php 里面;

function archives_list_SHe() {
     global $wpdb,$month;
     $lastpost = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_date <'" . current_time('mysql') . "' AND post_status='publish' AND post_type='post' AND post_password='' ORDER BY post_date DESC LIMIT 1");
     $output = get_option('SHe_archives_'.$lastpost);
     if(empty($output)){
         $output = '';
         $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'SHe_archives_%'");
         $q = "SELECT DISTINCT YEAR(post_date) AS year, MONTH(post_date) AS month, count(ID) as posts FROM $wpdb->posts p WHERE post_date <'" . current_time('mysql') . "' AND post_status='publish' AND post_type='post' AND post_password='' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC";
         $monthresults = $wpdb->get_results($q);
         if ($monthresults) {
             foreach ($monthresults as $monthresult) {
             $thismonth    = zeroise($monthresult->month, 2);
             $thisyear    = $monthresult->year;
             $q = "SELECT ID, post_date, post_title, comment_count FROM $wpdb->posts p WHERE post_date LIKE '$thisyear-$thismonth-%' AND post_date AND post_status='publish' AND post_type='post' AND post_password='' ORDER BY post_date DESC";
             $postresults = $wpdb->get_results($q);
             if ($postresults) {
                 $text = sprintf('%s %d', $month[zeroise($monthresult->month,2)], $monthresult->year);
                 $postcount = count($postresults);
                 $output .= '<ul class="archives-list"><li><span class="archives-yearmonth">' . $text . ' &nbsp;(' . count($postresults) . '&nbsp;篇文章)</span><ul class="archives-monthlisting">' . "\n";
             foreach ($postresults as $postresult) {
                 if ($postresult->post_date != '0000-00-00 00:00:00') {
                 $url = get_permalink($postresult->ID);
                 $arc_title    = $postresult->post_title;
                 if ($arc_title)
                     $text = wptexturize(strip_tags($arc_title));
                 else
                     $text = $postresult->ID;
                     $title_text = 'View this post, &quot;' . wp_specialchars($text, 1) . '&quot;';
                     $output .= '<li>' . mysql2date('d日', $postresult->post_date) . ':&nbsp;' . "<a href='$url' title='$title_text'>$text</a>";
                     $output .= '&nbsp;(' . $postresult->comment_count . ')';
                     $output .= '</li>' . "\n";
                 }
                 }
             }
             $output .= '</ul></li></ul>' . "\n";
             }
         update_option('SHe_archives_'.$lastpost,$output);
         }else{
             $output = '<div class="errorbox">Sorry, no posts matched your criteria.</div>' . "\n";
         }
     }
     echo $output;
 }

2、复制一份主题的 page.php 更名为 archives.php,然后在最顶端加入:

<?php
/*
Template Name: archives
*/
?>

3、再然后找到类似 ,在其下面加入如下代码

<a id="expand_collapse" href="#">全部展开/收缩</a>
<div id="archives"><?php archives_list_SHe(); ?></div>

 

进wp后台添加一新页面,在右侧栏模板选择 archives。

4、如果你的主题本身加载了 jQuery 库,那么继续把下面的 jQ 代码加上去,就会有滑动伸缩效果了。

<script type="text/javascript">
jQuery(document).ready(function() {
$('#expand_collapse,.archives-yearmonth').css({cursor:"s-resize"});
$('#archives ul li ul.archives-monthlisting').hide();
$('#archives ul li ul.archives-monthlisting:first').show();
$('#archives ul li span.archives-yearmonth').click(function(){$(this).next().slideToggle('fast');return false;});
$('#expand_collapse').toggle(
function(){
$('#archives ul li ul.archives-monthlisting').slideDown('fast');
},
function(){
$('#archives ul li ul.archives-monthlisting').slideUp('fast');
});
});
</script>

css 样式可以通过 #archive 来定义,ok,搞定。

 

今天换一种方式来实现Wordpress的文章归档页面,效果跟前一篇文章类似,都用到了Jquery来实现滑动伸缩效果。
下面我就说下简单的操作方法。
1、把下面的 archives_list_SHe 函数代码添加到主题的 functions.php 里面;

//日志归档
    class hacklog_archives
{
    function GetPosts()
    {
        global  $wpdb;
        if ( $posts = wp_cache_get( 'posts', 'ihacklog-clean-archives' ) )
            return $posts;
        $query="SELECT DISTINCT ID,post_date,post_date_gmt,comment_count,comment_status,post_password FROM $wpdb->posts WHERE post_type='post' AND post_status = 'publish' AND comment_status = 'open'";
        $rawposts =$wpdb->get_results( $query, OBJECT );
        foreach( $rawposts as $key => $post ) {
            $posts[ mysql2date( 'Y.m', $post->post_date ) ][] = $post;
            $rawposts[$key] = null;
        }
        $rawposts = null;
        wp_cache_set( 'posts', $posts, 'ihacklog-clean-archives' );;
        return $posts;
    }
    function PostList( $atts = array() )
    {
        global $wp_locale;
        global $hacklog_clean_archives_config;
        $atts = shortcode_atts(array(
            'usejs'        => $hacklog_clean_archives_config['usejs'],
            'monthorder'   => $hacklog_clean_archives_config['monthorder'],
            'postorder'    => $hacklog_clean_archives_config['postorder'],
            'postcount'    => '1',
            'commentcount' => '1',
        ), $atts);
        $atts=array_merge(array('usejs'=>1,'monthorder'   =>'new','postorder'    =>'new'),$atts);
        $posts = $this->GetPosts();
        ( 'new' == $atts['monthorder'] ) ? krsort( $posts ) : ksort( $posts );
        foreach( $posts as $key => $month ) {
            $sorter = array();
            foreach ( $month as $post )
                $sorter[] = $post->post_date_gmt;
            $sortorder = ( 'new' == $atts['postorder'] ) ? SORT_DESC : SORT_ASC;
            array_multisort( $sorter, $sortorder, $month );
            $posts[$key] = $month;
            unset($month);
        }
        $html = '<div class="car-container';
        if ( 1 == $atts['usejs'] ) $html .= ' car-collapse';
        $html .= '">'. "\n";
        if ( 1 == $atts['usejs'] ) $html .= '<a href="#" class="car-toggler">展开所有月份'."</a>\n\n";
        $html .= '<ul class="car-list">' . "\n";
        $firstmonth = TRUE;
        foreach( $posts as $yearmonth => $posts ) {
            list( $year, $month ) = explode( '.', $yearmonth );
            $firstpost = TRUE;
            foreach( $posts as $post ) {
                if ( TRUE == $firstpost ) {
                    $html .= '  <li><span class="car-yearmonth">+ ' . sprintf( __('%1$s %2$d'), $wp_locale->get_month($month), $year );
                    if ( '0' != $atts['postcount'] )
                    {
                        $html .= ' <span title="文章数量">(共' . count($posts) . '篇文章)</span>';
                    }
                    $html .= "</span>\n       <ul class='car-monthlisting'>\n";
                    $firstpost = FALSE;
                }
                $html .= '          <li>' .  mysql2date( 'd', $post->post_date ) . '日: <a target="_blank" href="' . get_permalink( $post->ID ) . '">' . get_the_title( $post->ID ) . '</a>';
                if ( '0' != $atts['commentcount'] && ( 0 != $post->comment_count || 'closed' != $post->comment_status ) && empty($post->post_password) )
                    $html .= ' <span title="评论数量">(' . $post->comment_count . '条评论)</span>';
                $html .= "</li>\n";
            }
            $html .= "      </ul>\n   </li>\n";
        }
        $html .= "</ul>\n</div>\n";
        return $html;
    }
    function PostCount()
    {
        $num_posts = wp_count_posts( 'post' );
        return number_format_i18n( $num_posts->publish );
    }
}
if(!empty($post->post_content))
{
    $all_config=explode(';',$post->post_content);
    foreach($all_config as $item)
    {
        $temp=explode('=',$item);
        $hacklog_clean_archives_config[trim($temp[0])]=htmlspecialchars(strip_tags(trim($temp[1])));
    }
}
else
{
    $hacklog_clean_archives_config=array('usejs'=>1,'monthorder'   =>'new','postorder'    =>'new');
}
$hacklog_archives=new hacklog_archives();

 
2、复制一份主题的 page.php 更名为 archives.php,然后在最顶端加入:

<?php
/*
Template Name: archives
*/
?>

3、再然后找到类似 ,在其下面加入如下代码

<h2>文章归档</h2>
        <p class="date"><strong><?php bloginfo('name'); ?></strong>目前共有文章:  <?php echo $hacklog_archives->PostCount();?>篇  </p>
    <?php echo $hacklog_archives->PostList();?>

 
进wp后台添加一新页面,在右侧栏模板选择 archives。
4、如果你的主题本身加载了 jQuery 库,那么继续把下面的 jQ 代码加上去,就会有滑动伸缩效果了。

<script type="text/javascript">
            jQuery(document).ready(function() {
                jQuery('.car-collapse').find('.car-monthlisting').hide();
                jQuery('.car-collapse').find('.car-monthlisting:first').show();
                jQuery('.car-collapse').find('.car-yearmonth').click(function() {
                    jQuery(this).next('ul').slideToggle('fast');
                });
                jQuery('.car-collapse').find('.car-toggler').click(function() {
                    if ( '展开所有月份' == jQuery(this).text() ) {
                        jQuery(this).parent('.car-container').find('.car-monthlisting').show();
                        jQuery(this).text('折叠所有月份');
                    }
                    else {
                        jQuery(this).parent('.car-container').find('.car-monthlisting').hide();
                        jQuery(this).text('展开所有月份');
                    }
                    return false;
                });
            });
</script>

 
css 样式如下,当然你也可以自定义,ok,搞定。

.car-collapse .car-yearmonth { cursor: s-resize; }
.car-container{ width:666 px; }
a.car-toggler{line-height:30px; font-size:14px; color:#c30}
.car-list li{list-style:none; line-height:24px}
.car-list li ul{padding-left:30px}

 

 

来自:http://www.weisay.com/blog/wordpress-archives.html

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。