Support » Fixing WordPress » Adding an anchor to previous_post_links and next_post_links

  • Been trying to do this all day but not having any luck!

    In my WordPress theme I have a gallery at the top and blog posts below it. Each time I click the previous or next post links it goes to the top which I don’t want so I’ve created an anchor called #blog and placed in my html below the gallery. How do add the anchor to the previous_post_links and next_posts_links to make it work? If it can’t be done, is there a JavaScript solution for it?

Viewing 1 replies (of 1 total)
  • You can use a custom function to add arguments to the links. Here is the code for the function:

    function mam_add_query_arg ($key,$value,$link) {
       // Adds the parameter $key=$value to $link, or replaces it if already there.
       // Necessary because add_query_arg fails on previous/next_post_link.
       if (strpos($link,'href')) {
         $hrefpat = '/(href *= *([\"\']?)([^\"\' ]+)\2)/';
       } else {
         $hrefpat = '/(([\"\']?)(http([^\"\' ]+))\2)/';
       }
       if (preg_match($hrefpat,$link,$matches)) {
          $url = $matches[3];
          $newurl = add_query_arg($key,$value,$url);
          // echo '<p>OLDURL:' . htmlspecialchars($url) . '</p>';
          // echo '<p>NEWURL:' . htmlspecialchars($newurl) . '</p>';
          $link = str_replace($url,$newurl,$link);
       }
    
       return $link;
    }

    Then replace the call to next_posts_link() like this:

    echo mam_add_query_arg( 'mykey','myvalue',get_next_posts_link());

    Do the same for previous_posts_link().

    Be sure to put the correct arguments to the previous/next_posts_link() calls!

Viewing 1 replies (of 1 total)
  • The topic ‘Adding an anchor to previous_post_links and next_post_links’ is closed to new replies.