Add #anchor to next/previous_post_link

I have tried to figure out to change the previous_post_link by following the Codex but I can’t figure it out.
Same for the next_post_link.

I just want to have a simple link but with an #anchor tag added.

All I get is a changed LinkName – the url stays untouched.

I could do it with javascript, but this isn’t the way I want to do it – I would like to know how to do it with WordPress tools.

Any hint would be great.

Solutions Collecting From Web of "Add #anchor to next/previous_post_link"

This seems to do the trick:

add_filter( 'next_post_link',     'wpse_post_link', 10, 4 );
add_filter( 'previous_post_link', 'wpse_post_link', 10, 4 );

function wpse_post_link( $output, $format, $link, $post )
    if( $url = get_permalink( $post ) ) 
        $output = str_replace( $url, $url . '#anchor', $output );

    return $output;

i.e. appending the #anchor to the previous/next permalinks.

ps: I removed the WP_Rewrite::using_permalink() check, since we actually don’t need it, example.tld?p=123#anchor should work as well.