previous_posts_link()与next_post_lnik()这两个函数相信各位wordpress主题开发者一定不陌生,这两个函数是wordpress用来调用当前文章的前一篇以及后一篇文章的。但是有些时候我们为了提高网站PV提高用户体验想多调用几篇文章,例如调用当前文章的前三篇文章以及后三篇文章那该怎么调用呢?查看了下wordpress的官方文档,显然没有现成的代码和函数可用。那么只好自己动手丰衣足食了。以下代码参考自wordpress默认函数get_adjacent_post函数修改而来:
- function ztmao_get_post( $previous = true, $number = 1 ) {
-
-
- global $post, $wpdb;
- if ( emptyempty( $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";
-
- $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 = v7v3_get_post(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 = ztmao_get_post(false,3);
- foreach( $nextposts as $postt ){
- echo '<li><a href="'.get_permalink($postt->ID).'" title="'.$postt->post_title .'">'.$postt->post_title .'</a></li>';
- };
- ?>
- </ul>
注:此文参考了阿树大神的wordpress教程而来。