WordPress.org

Ready to get started?Download WordPress

Forums

Adding an anchor to previous_post_links and next_post_links (2 posts)

  1. sugarMonsterx
    Member
    Posted 1 year ago #

    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?

  2. vtxyzzy
    Member
    Posted 1 year ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.