阅读:3106回复:0
wordpress开发教程:获取当前文章的前几篇以及后几篇文章
[tr][td]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 [*] 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"; [*] //获取当前文章所属分类,可以同属多个分类,如果是自定义的分类法,将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文件中即可,调用该函数的时候会返回一个数组,使用示例: [*]本篇教程之前的几篇教程是 [*] [*] [*] [*] 本篇教程之后的几篇教程是 [*] [*] [*] </strong> [/td][/tr] |
|