3

I've been using get_adjacent_post() to determine the previous and next posts. How would I go about determining the next and previous links to posts matching the same tag as the current post? It seems this function allows you to do this with posts in the same category, but not with the same tag.

2 Answers 2

5

get_adjacent_posts() has several filters for components of generated SQL query, including:

  • get_{$adjacent}_post_join
  • get_{$adjacent}_post_where

Where $adjacent can be next or previous. Source.

So there is no easy way to flip it from categories to tags, but you can manipulate SQL query and add own conditions (or change to them completely).

0
0

This function is just modified get_adjacent_post:

/* better get_adjacent_post */
function get_adjacent_post_by_taxonomy($tagID, $previous){
    global $wpdb;

    if ( ! $post = get_post() )
        return null;

    $current_post_date = $post->post_date;

    $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 AND tt.term_id IN (" . $tagID . ")";

    $adjacent = $previous ? 'previous' : 'next';
    $op = $previous ? '<' : '>';
    $order = $previous ? 'DESC' : 'ASC';

    $join  = apply_filters( "get_{$adjacent}_post_join", $join );
    $where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish'", $current_post_date, $post->post_type));
    $sort  = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" );

    $query = "SELECT p.ID FROM $wpdb->posts AS p $join $where $sort";
    $query_key = 'adjacent_post_' . md5($query);
    $result = wp_cache_get($query_key, 'counts');
    if ( false !== $result ) {
                if ( $result )
                        $result = get_post( $result );
                return $result;
        }

        $result = $wpdb->get_var( $query );
        if ( null === $result )
                $result = '';

        wp_cache_set($query_key, $result, 'counts');

        if ( $result )
                $result = get_post( $result );

        return $result;
}

Pass a category or tag's term_taxonomy_id to this functions $tax_id to use for a tag or a category. I use it like:

$tags = get_the_tags();
        if($tags) :
            foreach($tags as $tag) : ?>
...
                    <?php $prevTagPost = get_adjacent_post_by_taxonomy($tag->term_taxonomy_id,true); if (!empty( $prevTagPost )): ?>

etc.

Just like get_adjacent_post, the bool $previous toggles between previous/next.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.