function get_adjacent_post($in_same_category = false, $previous = true, $excluded_categories = '', $taxonomy = '') {
global $post, $wpdb;
if ( empty( $post ) || ( !empty($taxonomy) && !taxonomy_exists( $taxonomy ) ) )
return null;
$current_post_date = $post->post_date;
$join = '';
$posts_in_ex_cats_sql = '';
if ( $in_same_category || !empty($excluded_categories) ) {
$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_category ) {
$cat_array = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));
$join .= " AND tt.taxonomy = '".$taxonomy."' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
}
$posts_in_ex_cats_sql = "AND tt.taxonomy = '".$taxonomy."'";
if ( !empty($excluded_categories) ) {
$excluded_categories = array_map('intval', explode(' and ', $excluded_categories));
if ( !empty($cat_array) ) {
$excluded_categories = array_diff($excluded_categories, $cat_array);
$posts_in_ex_cats_sql = '';
}
if ( !empty($excluded_categories) ) {
$posts_in_ex_cats_sql = " AND tt.taxonomy = '".$taxonomy."' AND tt.term_id NOT IN (" . implode($excluded_categories, ',') . ')';
}
}
}
$adjacent = $previous ? 'previous' : 'next';
$op = $previous ? '<' : '>';
$order = $previous ? 'DESC' : 'ASC';
$join = apply_filters( "get_{$adjacent}_{$taxonomy}_join", $join, $in_same_category, $excluded_categories );
$where = apply_filters( "get_{$adjacent}_{$taxonomy}_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date, $post->post_type), $in_same_category, $excluded_categories );
$sort = apply_filters( "get_{$adjacent}_{$taxonomy}_sort", "ORDER BY p.post_date $order LIMIT 1" );
$query = "SELECT p.* FROM $wpdb->posts AS p $join $where $sort";
$query_key = "adjacent_{$taxonomy}_" . 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;
}