Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Created July 20, 2017 00:48
Show Gist options
  • Save jongacnik/ad4488a8056db6fe4a37742c15c978eb to your computer and use it in GitHub Desktop.
Save jongacnik/ad4488a8056db6fe4a37742c15c978eb to your computer and use it in GitHub Desktop.
Simple WP Adjacent Post
<?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;
}
<?php
$prev = get_adjacent_post_basic('prev');
$next = get_adjacent_post_basic('next');
@jongacnik
Copy link
Author

jongacnik commented Jul 20, 2017

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:

<?php

function get_adjacent_promoted_posts ($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 
      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 $operator '$date'
        AND p.post_type = 'post'
        AND p.post_status = 'publish'
        AND tt.taxonomy = 'rating'
        AND tt.term_id = '1778'
      ORDER by 
        p.post_date $order
      LIMIT 
        1
    ");  

    return $p;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment