本站中的教程都是成系列的文章,所以为了提高用户体验,我在每篇教程的后面列出当前文章的前 3 篇文章和后 3 篇文章,这个可以当成是相关文章吧。
代码乃是我参考 wp 自带的 get_adjacent_post 函数修改而来,get_adjacent_post 函数是 WordPress 用来获取上一篇和下一篇文章的基本函数。哎呀文采不好就不废话了函数代码:
函数作用:获取当前文章同分类下的前几篇文章和后几篇文章
参数:$previous 为 true 时获取之前的文章, 为 false 的时候获取之后的文章
$number 为获取文章数量
- //author:www.ashuwp.com
- function ashu_get_adjacent_posts( $previous = true, $number = 1 ) {
- //global 当前文章变量 $post 和数据库操作类 wpdb
- global $post, $wpdb;
- if ( empty( $post ) )
- return null;
- $current_post_date = $post->post_date;//当前文章的时间
- $join = ”;
- $posts_in_ex_cats_sql = ”;
- //加入表
- $join = ” INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id”;
- //获取当前文章所属分类, 可以同属多个分类, 如果是自定义的分类法, 将 category 换成对应的分类法即可
- $cat_array = wp_get_object_terms($post->ID, ‘level’, array(‘fields’ => ‘ids’));
- $join .= ” AND tt.taxonomy = ‘level’ AND tt.term_id IN (“ . implode(‘,’, $cat_array) . “)”;
- //判断时间是大于还是小雨
- $op = $previous ? ‘<‘ : ‘>’;
- //排序
- $order = $previous ? ‘DESC’ : ‘ASC’;
- $where = $wpdb->prepare(“WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = ‘publish’ “, $current_post_date, $post->post_type);
- $sort = “ORDER BY p.post_date $order LIMIT 0, $number”;
- $query = “SELECT p.* FROM $wpdb->posts AS p $join $where $sort”;
- $query_key = ‘adjacent_post_’ . md5($query);
- $result = wp_cache_get($query_key, ‘counts’);
- if ( false !== $result )
- return $result;
- $result = $wpdb->get_results(“SELECT p.* FROM $wpdb->posts AS p $join $where $sort”);
- if ( null === $result )
- $result = ”;
- wp_cache_set($query_key, $result, ‘counts’);
- return $result;
- }
将该函数放在主题的 functions.php 文件中即可,调用该函数的时候会返回一个数组,使用示例:
- <h4> 本篇教程之前的几篇教程是</h4>
- <ul>
- <?php
- $preposts = ashu_get_adjacent_posts(true,3);
- foreach( $preposts as $postt ){
- echo ‘<li><a href=“‘.get_permalink($postt->ID).'” title=“‘.$postt->post_title .'”>’.$postt->post_title .'</a></li>’;
- };
- ?>
- </ul>
- <h4> 本篇教程之后的几篇教程是</h4>
- <ul>
- <?php
- $nextposts = ashu_get_adjacent_posts(false,3);
- foreach( $nextposts as $postt ){
- echo ‘<li><a href=“‘.get_permalink($postt->ID).'” title=“‘.$postt->post_title .'”>’.$postt->post_title .'</a></li>’;
- };
- ?>
- </ul>
效果预览: