WordPress.org

Ready to get started?Download WordPress

Forums

How to use wp pagination to show next / previous post of a given post tag? (5 posts)

  1. davetionary
    Member
    Posted 10 months ago #

    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?

  2. bcworkz
    Member
    Posted 10 months ago #

    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.

  3. davetionary
    Member
    Posted 10 months ago #

    This sounds plausible!

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

  4. bcworkz
    Member
    Posted 10 months ago #

    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;
    }
  5. davetionary
    Member
    Posted 10 months ago #

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

    Thanks SO much for your replies!

Reply

You must log in to post.

About this Topic