wordpress主题常用的代码
2010-07-20 by zhiwei
很多同学的wordpress博客主题侧边栏都有最新文章、随机文章、最新评论等等内容,而单篇文章下方也会加上版权信息,我之前添加版权信息就是在写每篇文章时,在最后加上,但是这样太麻烦,自己在网上搜索一下,然后又仿照一些知名博客的相应设置自己也在博客文章页面加上了版权信息,由于最近比较忙,一直没空写出来,今天就把它写出来与大家分享一下。
1. 最新/随机文章
1 2 3 4 5 6 7 | global $post;
$myposts = get_posts('numberposts=9&offset=1&orderby=rand');
foreach($myposts as $post) :
setup_postdata($post);
?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; |
最新/随机文章用的是wordpress现成的函数调用,上述代码中的numberposts=9是指显示9篇文章,orderby=rand意思是随机显示,如果是orderby=date就是最新文章了,当然还得order=desc,意思是按日期降序排列,懂sql语言的同学很容易就能看明白,这里有更详细的官方介绍,不过是英文的。这个地方是获得最新文章的另一种方法。
2. 最新评论
1 2 3 4 5 6 7 | $comments = get_comments('number=9&$status=approve&offset=1');
foreach($comments as $comm) :
$comm->comment_content=mb_substr($comm->comment_content,0,20);
?>
<li><a href="<?php echo(get_permalink($comm->comment_post_ID)); ?>#comment-<?php echo($comm->comment_ID); ?>" title="view the entire comment by <?php echo($comm->comment_author); ?>"><?php echo($comm->comment_content); ?></a></li>
<?php
endforeach; |
最新评论这个代码用了我很长时间才写好,一般网上的方法都是直接去查询数据库,写一大堆代码,太麻烦了,我在wordpress官方文档上找到了这个方法,很好用,不过总是最后一条评论显示不出来,目前也没有找到原因。代码说明我就不写了,很简单的。
3. 版权信息
1 2 3 4 5 6 7 8 9 10 11 12 | function insertNote($content) { if(is_single()||is_feed()) { $content.='<p style="font-weight: bold;">© '. get_the_time('Y').', <a href="http://chenzhiwei.net">chenzhiwei.net</a>. 版权所有. <br />'; $content.=''; $content.= '本文永久链接:<a title="'.get_the_title().'" href="'.get_permalink().'">'.get_permalink().'</a></p>'; } if(is_feed()) { $content.="<hr />"; } return $content; } add_filter ('the_content', 'insertNote'); |
版权信息是在主题支持函数里写一个函数,就可以了。也可以将feed里也加入版权信息。以上代码就是我博客里的用,可以参考一下。相关图片如下:


4. 存档页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <div class="archive"> <strong>by page:</strong> <ul> <?php wp_list_pages('title_li='); ?> </ul> <strong>by month:</strong> <ul> <?php wp_get_archives('type=monthly'); ?> </ul> <strong>by category:</strong> <ul> <?php wp_list_categories('sort_column=name&title_li='); ?> </ul> </div> <div class="archive"> <strong>by post:</strong> <ul> <?php wp_get_archives('type=postbypost&limit=100'); ?> </ul> </div> |
有些同学一直在用插件实现文档存档,不过,我认为博客里最好还是少用插件,这样可以减轻服务器负担,也减少了升级插件的麻烦,下面就是我存档页面用的代码。
以上就是我博客里用到的一些代码,以后再用其他代码时,我会及时补充上来。
© 2010, chenzhiwei.net. 版权所有.
本文永久链接:http://chenzhiwei.net/2010/07/wordpress-useful-code/

这篇文章好,慢慢研究。
写得好,先收藏了!
版权信息,就是你每篇文章下的文章地址吧》?
是这样的,加上版权信息还有助于搜索引擎判断内容的作者,有助于SEO。
没有这样的作用吧
呵呵,这样是希望有良心的站长复制你文章的时候能够保留为你增加一个外链
有没有’相关文章‘的代码?
这个目前我还没发现。