Skip to content

Instantly share code, notes, and snippets.

@andandehei
Last active January 3, 2016 07:59
Show Gist options
  • Save andandehei/8432935 to your computer and use it in GitHub Desktop.
Save andandehei/8432935 to your computer and use it in GitHub Desktop.
代码实现本篇文章的前几篇和后几篇功能
<? php
//前几篇后几篇文章
function wenchenhk_get_post( $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, 'category', array('fields' => 'ids'));
$join .= " AND tt.taxonomy = 'category' 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;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment