skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    Thanks so much @imhvost,

    I solved it this way. At the beginning of each post the WordPress theme inserts the "layout" ID which represents the exact beginning of the content. With this function, where I hope I haven't made any mistakes, each post is loaded exactly at that point.

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

  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search