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 );
  post_template($theme_query);
}

Leave a Comment