Created
July 20, 2017 00:48
-
-
Save jongacnik/ad4488a8056db6fe4a37742c15c978eb to your computer and use it in GitHub Desktop.
Simple WP Adjacent Post
This file contains hidden or 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_post_basic ($direction = 'prev', $date = '') { | |
global $wpdb, $post; | |
if( empty( $date ) ) | |
$date = $post->post_date; | |
$operator = $direction == 'prev' ? '<' : '>'; | |
$order = $direction == 'prev' ? 'DESC' : 'ASC'; | |
$p = $wpdb->get_results(" | |
( | |
SELECT | |
p.post_date, | |
p.post_title, | |
p.ID | |
FROM | |
$wpdb->posts AS p | |
WHERE | |
p.post_date $operator '$date' | |
AND p.post_type = 'post' | |
AND p.post_status = 'publish' | |
ORDER by | |
p.post_date $order | |
LIMIT | |
1 | |
) | |
ORDER by post_date ASC "); | |
return $p; | |
} |
This file contains hidden or 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 | |
$prev = get_adjacent_post_basic('prev'); | |
$next = get_adjacent_post_basic('next'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very simple starting point for writing a more complex adjacent post query. For example, here is a query which only returns posts with a specific term from a custom taxonomy: