全百科精品资源分享
免费优质资源下载平台

纯代码给WordPress文章添加自定义排序功能

播放按钮
全百科网免费发布推广信息
文章目录

WordPress 默认文章列表排序方式是根据发布时间,也就是最新的文章显示在列表最前面,那么我们如果想自定义文章的排序呢?今天我们通过配置文章查询函数来实现文章列表的自定义排序。

如按修改时间、按评论数,甚至是按照阅读量排序?WordPress 文章查询有若干种方法,本文仅拿 query_posts($args)数据查询来说,通过配置其中的 orderby 参数来实现各种排序。

操作方法

 <?php
    $args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => '10',
    'orderby' => 'date',
    'order' => 'DESC',
    'caller_get_posts' => 1,
 
    );
    $query_posts = new WP_Query();
    $query_posts->query($args);
    while( $query_posts->have_posts() ) { $query_posts->the_post(); ?>
    <li>
    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
    <?php the_title(); ?>
    </a>
    </li>
    <?php } wp_reset_query();?>

上述查询函数中,我们通过修改 orderby 后面的值来,实现不同的排序方式。

一般用法

按发布日期排序 orderby=date?

按修改时间排序 orderby=modified

按文章 ID 排序 orderby=ID

按评论最多排序 orderby=comment_count

按标题排序 orderby=title

随机排序 orderby=rand

特殊用法

如果我们想通过浏览量来排序呢?要知道 WordPress 默认是没有浏览量这个功能的,但是大多数的用户都通过主题或者插件实现了文章阅读量,其原理无一例外是通过自定义栏目增加阅读量的统计。因此我们可以通过自定义栏目的值大小来实现阅读量排序。首先确定你的文章阅读量的自定义蓝色名称,一般为 views 然后我们将查询函数进行修改即可,得到如下代码:

    <?php
    $args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => '10', /* 显示几条 */
    'meta_key' => 'views',/* 此处为你的自定义栏目名称 */
    'orderby' => 'meta_value_num', /* 配置排序方式为自定义栏目值 */
    'order' => 'DESC', /* 降序排列 */
    'caller_get_posts' => 1,
 
    );
    $query_posts = new WP_Query();
    $query_posts->query($args);
    while( $query_posts->have_posts() ) { $query_posts->the_post(); ?>
    <li>
    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
    <?php the_title(); ?>
    </a>
    </li>
    <?php } wp_reset_query();?>

还有一个常见的查询函数:

    <?php
    $posts = get_posts(“numberposts=10&meta_key=views&orderby=meta_value_num&order=desc”);
    foreach( $posts as $post ) :
    ?>
    ……
    <?php endforeach; ?>

WordPress 是非常强大的,通过各种自定义配置,可以实现各种各样的需求。

Download Best WordPress Themes Free Download
Premium WordPress Themes Download
Download Premium WordPress Themes Free
Premium WordPress Themes Download
free download udemy course
download huawei firmware
Premium WordPress Themes Download
free online course

搜一下 获取更多

本文由全百科网分享提供,分享更多精品资源,帮助你我共同成长。

赞(0)
全百科网 » 纯代码给WordPress文章添加自定义排序功能
本站内容均来自网络收集,转载内容不代表本网站的观点及意见,仅供用户参考和借鉴。如对稿件内容及版权问题有疑议,请及时联系全百科官方邮箱: smtsg@foxmail.com

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址