wordpressanchorpermalinks

How to use anchor in Wordpress permalinks


I'll try to explain my need as best I can. When I create a new post in WordPress, the permalink is automatically generated. The permalink is also present within the post and can be modified manually later. If I wanted to add an anchor the # symbol is replaced by -. Same thing for myUrl/#my-anchor becomes myUrl-my-anchor and this of course doesn't work.

I would like the ability to provide a link to a post that, when clicked, allows the post to be viewed, or scrolled, at a specific position. Even a function that calls a specific #layout ID that I have in every single post would be perfect.

Searching the web I found different topics but they all talk about how to create anchors using the text editor but that's not what I'm looking for.

I use a child theme so I could also work on the functions.php.

Does anyone have a solution to this?

Thank you very much


Solution

  • WordPress has special filters, such as post_link, page_link, post_type_link, category_link, and so on.
    For example, if you want to add a link hash to a post with id === 123, do something like this:

    add_filter( 'post_link', 'my_post_link', 10, 3 );
    
    function my_post_link( $permalink, $post, $leavename ) {
        if ( $post->ID === 123 ) {
            $permalink = $permalink . '#hash';
        }
        return $permalink;
    }