Support » Plugins » Hacks » How to use wp pagination to show next / previous post of a given post tag?

  • I’m trying to find a way to modify wordpress’ pagination to a particular case of mine. I wonder if anyone can help here.

    I’d like to ensure that the next and previous post buttons at the bottom of my post pages only show the next and previous posts that share the same tag as the post you’re viewing. Posts will only have one tag assigned.

    Can anyone think of a way to do this?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz


    Curiously, the post link functions do have a facility to link to the next post in the same category, though many themes do not avail themselves of this. In any case, the same functions have no such facility for tags, the ‘category’ taxonomy is hard coded in. However, you could alter your template to pass true for the ‘in_same_cat’ parameter even though it’s for a tag archive. Then hook into the “get_{$adjacent}_post_join” filter (where $adjacent is either ‘next’ or ‘previous’). Your callback is passed the JOIN portion of the query. Replace ‘category’ with ‘post_tag’ and replace the term list with the term ID of the current tag.

    The one sticking point is how does your callback know what the current tag is? I’m not sure, but it should be in the global $wp_query somewhere.

    This sounds plausible!

    If you wouldn’t mind: what would a modified get_{$adjacent}_post look like if configured this way?

    Moderator bcworkz


    Needs more investigation and work, but basically something like this:

    add_filter('get_previous_post_join', 'bcw_cat2tag', 10, 3);
    add_filter('get_next_post_join', 'bcw_cat2tag', 10, 3);
    function bcw_cat2tag( $join, $in, $out) {
      global $wp_query;
      if(/* Logic here if hook is NOT for tag posts */) return $join;
      $tag_id = $wp_query->get_var('/*????*/'); //need correct tag key here (if it even exists, otherwise ????)
      // $in has potential as a way to pass tag ID if not in $wp_query
      $join = str_replace('category', 'post_tag', $join);
      //next line needs work, especially the regexp
      $join = preg_replace('/tt\.term_id\sIN\s\(.*\)/', "tt.term_id IN ($tag_id)")
      return $join;

    This is very helpful and gives me something to run with.

    Thanks SO much for your replies!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to use wp pagination to show next / previous post of a given post tag?’ is closed to new replies.