下面是@Jan Fabry在上文中提到的复制/粘贴编辑版本(肯定不是最优雅的解决方案,但应该可以):
/**
* Retrieve adjacent post.
*
* Can either be next or previous post.
*
*
* @param bool $in_same_tag Optional. Whether post should be in same category.
* @param string $excluded_tags Optional. Excluded tags IDs.
* @param bool $previous Optional. Whether to retrieve previous post.
* @return mixed Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
*/
function get_adjacent_post_by_tag($in_same_tag = false, $excluded_tags = \'\', $previous = true) {
global $post, $wpdb;
if ( empty( $post ) )
return null;
$current_post_date = $post->post_date;
$join = \'\';
$posts_in_ex_tags_sql = \'\';
if ( $in_same_tag || !empty($excluded_tags) ) {
$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";
if ( $in_same_tag ) {
$tag_array = wp_get_object_terms($post->ID, \'post_tag\', array(\'fields\' => \'ids\'));
$join .= " AND tt.taxonomy = \'post_tag\' AND tt.term_id IN (" . implode(\',\', $tag_array) . ")";
}
$posts_in_ex_tags_sql = "AND tt.taxonomy = \'post_tag\'";
if ( !empty($excluded_tags) ) {
$excluded_tags = array_map(\'intval\', explode(\' and \', $excluded_tags));
if ( !empty($tag_array) ) {
$excluded_tags = array_diff($excluded_tags, $tag_array);
$posts_in_ex_tags_sql = \'\';
}
if ( !empty($excluded_tags) ) {
$posts_in_ex_tags_sql = " AND tt.taxonomy = \'post_tag\' AND tt.term_id NOT IN (" . implode($excluded_tags, \',\') . \')\';
}
}
}
$adjacent = $previous ? \'previous\' : \'next\';
$op = $previous ? \'<\' : \'>\';
$order = $previous ? \'DESC\' : \'ASC\';
$join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_tag, $excluded_tags );
$where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = \'publish\' $posts_in_ex_tags_sql", $current_post_date, $post->post_type), $in_same_tag, $excluded_tags );
$sort = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" );
$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_row("SELECT p.* FROM $wpdb->posts AS p $join $where $sort");
if ( null === $result )
$result = \'\';
wp_cache_set($query_key, $result, \'counts\');
return $result;
}