Add post/page ID to inserted links within the_content

Within the main content editor of posts and pages, we can insert multiple links to other posts/pages:

<a href="">Hello World</a>

What I am trying to do is get WordPress to automatically add the ID of, in this case, the Hello World post to the link. To try and clearly explain what I’m wanting, imagine I’m writing a new blog post and I put a link within the new blog post to my existing Hello World post.

<a id="4" href="">Hello World</a>

Where in the above example our Hello World post has the ID of 4. I have been studying this answer to a different question but I haven’t quite figured out how to get the ID of the post/page I am linking to and add it to the anchor element. Incase we have more than one link pointing to the same post/page it might be safer to use the rel attribute instead:

<a href="" rel="4">Hello World</a>

Solutions Collecting From Web of "Add post/page ID to inserted links within the_content"

This is the solution I arrived at with thanks to the pointer from @bravokeyl

So, to be clear it does not add the ID’s to links but by using the link slug I’m able to get the ID which is a solution for what I need. I’m using JS to pass the URL into this function and then stripping it down to the slug only which is used within get_page_by_path which then returns the ID for that post.

It’s part of what I’m working on to build an Ajax powered theme. This approach also solves the issue of having multiple links with the same ID’s.

function local_post_init() {
  /** Get post ID from slug **/
  $page_slug = $_POST['id'];
  $page_data = get_page_by_path(basename( untrailingslashit( $page_slug ) ) , OBJECT, 'post');
  $page_id = $page_data->ID;
  /** $page_id holds our ID which we then use in our query */
  $args = array( 'p' => $page_id );
  $theme_query = new \WP_Query( $args );