Appending anchor tag to next post

You can alter the links for next_post_link and previous_post_link with a filter.

function alter_npppl_wpse_100919($link) {
  return preg_replace('/href="https://wordpress.stackexchange.com/questions/100919/([^"]+)"https://wordpress.stackexchange.com/",'href="$1#something"',$link);
}
add_filter('next_post_link','alter_npppl_wpse_100919');
add_filter('previous_post_link','alter_npppl_wpse_100919');

The URL you get will be the default URL plus #content. If your site is generating /page/2/ then the final URL will be /page/2/#content. If you don’t want that trailing slash– the one before the #— you will have to pass the match through a callback.

function alter_npppl_noslash_cb_wpse_100919($match) {
  return 'href="'.untrailingslashit($match[1]).'#content"';
}
function alter_npppl_v2_wpse_100919($link) {
  return preg_replace_callback('/href="https://wordpress.stackexchange.com/questions/100919/([^"]+)"https://wordpress.stackexchange.com/",'alter_npppl_noslash_cb_wpse_100919',$link);
}
function alter_npppl_wpse_100919($link) {
  return preg_replace('/href="https://wordpress.stackexchange.com/questions/100919/([^"]+)"https://wordpress.stackexchange.com/",'href="$1#something"',$link);
}
add_filter('next_post_link','alter_npppl_v2_wpse_100919');
add_filter('previous_post_link','alter_npppl_v2_wpse_100919');

If you site is using the trailing slash I would not remove it. You will likely end up with unnecessary redirects if you do.

#something can be any id on the page. If you had <div id="content" then adding #content should cause that div to scroll into view on page load.

Leave a Comment