0

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 2

0

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much @imhvost, this is a good solution, but I would have to add a new post ID every time. It would be decisive to be able to have a function that is not limited to a post ID but which, for example, can consider all the posts that will have #readmore. Can this be done?
if ( $post->ID === 121 ) is just an example. You can take $post->post_content and search a block with id="readmore". Or create a meta field for the posts (for example the is_has_readmore checkbox), and apply the 'post_link' filter to those posts that have is_has_readmore.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.