好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

WordPress增加文章排序方式

露兜博客首页的访客可自行选择文章排序方式的效果是怎么做的,今天就来给大家分享这个文章排序效果的实现过程。

其实实现过程也比较简单,一个是构造链接,另外一个是使用query_posts来改变一下主循环就可以了。
构造链接
链接主要用于传递GET参数,让PHP程序知道你到底想怎么排序。在主题的index.php中你需要的位置插入以下代码,用于输出排序按钮的HTML,这个排序按钮的样式,你再自己写写css咯。需要注意的是以下代码会自动获取当前用户已选择的排序方式,并给这个排序按钮的 li 添加了class="current"

<h4>文章排序</h4>  <ul>  <li><a <?php  if  ( isset($_GET[ 'order' ]) && ($_GET[ 'order' ]== 'rand' ) ) echo  'class="current"' ; ?> href= "/?order=rand"  rel= "nofollow" >随机阅读</a></li>  <li><a <?php  if  ( isset($_GET[ 'order' ]) && ($_GET[ 'order' ]== 'commented' ) ) echo  'class="current"' ; ?> href= "/?order=commented"  rel= "nofollow" >评论最多</a></li>  <li><a <?php  if  ( isset($_GET[ 'order' ]) && ($_GET[ 'order' ]== 'alpha' ) ) echo  'class="current"' ; ?> href= "/?order=alpha"  rel= "nofollow" >标题排序</a></li>  </ul>  


改变主循环
首先你得先在主题的index.php中找到以下语句:

复制代码

代码如下:


if (have_posts()) 


然后在这句之前添加以下代码:

复制代码

代码如下:


if ( isset($_GET['order']) )
{
switch ($_GET['order'])
{
case 'rand' : $orderby = 'rand'; break;
case 'commented' : $orderby = 'comment_count'; break;
case 'alpha' : $orderby = 'title'; break;
default : $orderby = 'title';
}</p> <p> global $wp_query;
$args= array('orderby' => $orderby, 'order' => 'DESC');</p> <p> $arms = array_merge($args, $wp_query->query);
query_posts($arms);
}</p> <p>if (have_posts())

 

好了,就这么简单,复制粘贴,轻轻松松实现排序效果.

查看更多关于WordPress增加文章排序方式的详细内容...

  阅读:43次