Created
March 28, 2015 00:31
-
-
Save N-Molham/c451dbe776f3cba90cb0 to your computer and use it in GitHub Desktop.
Get next/previous post by entry date
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 | |
/** | |
* Get next/preview post by post_date | |
* | |
* @param int|WP_Post $post | |
* @param boolean $next_post | |
* @return WP_Post|WP_Error | |
*/ | |
function get_next_prev_post_by_date( $post, $next_post = true ) | |
{ | |
global $wpdb; | |
// get current post data | |
if ( !is_a( $post, 'WP_Post' ) ) | |
$post = get_post( $post ); | |
// build select SQL query | |
$query = "SELECT * FROM {$wpdb->posts}"; | |
$query .= " WHERE post_date ". ( $next_post ? '>' : '<' ) ." %s"; | |
$query .= " AND ID NOT IN (%d)"; | |
$query .= " ORDER BY post_date DESC LIMIT 1"; | |
// run query | |
$target_post_row = $wpdb->get_row( $wpdb->prepare( $query, $post->ID, $post->post_date ) ); | |
// return post object if found | |
if ( $target_post_row ) | |
return new WP_Post( $target_post_row ); | |
// return error if no match found | |
return new WP_Error( 'no_match_found', __( 'No matched post found' ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment