Last active
August 29, 2015 14:02
-
-
Save jongacnik/777ad3909682c52ac486 to your computer and use it in GitHub Desktop.
Custom Wordpress adjacent post query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_adjacent_posts_clean($prev = true, $limit = 1, $exclude = '', $date = '') { | |
global $wpdb, $post; | |
if( empty( $date ) ) | |
$date = $post->post_date; | |
$limit = absint( $limit ); | |
if( !$limit ) | |
return; | |
$prev_and_next = $prev ? '<' : '>'; | |
$exclude_string = (!empty($exclude)) ? 'AND tt1.term_id NOT IN(' . $exclude . ')' : ''; // put fallback in for array | |
$p = $wpdb->get_results( " | |
( | |
SELECT p.post_date, p.post_title | |
FROM $wpdb->posts AS p | |
INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id | |
INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id | |
WHERE | |
p.post_date " . $prev_and_next . " '$date' | |
AND p.post_type = 'post' | |
AND p.post_status = 'publish' | |
AND tt.taxonomy = 'category' | |
" . $exclude_string . " | |
ORDER by | |
p.post_date DESC | |
LIMIT | |
$limit | |
) | |
ORDER by post_date ASC "); | |
return $p; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isn't really meant to be used as is, there's some spots where this query would break. Just a good starting point if wanting to write a more custom adjacent post query than what is provided by WP core.
Original query modified from here