3

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

<a href="http://example.com/hello-world/">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="http://example.com/hello-world/">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="http://example.com/hello-world/" rel="4">Hello World</a>
3
  • Do you wan to add id to the links that were already added or the links that will be added in the future using WP Visual editor ?
    – bravokeyl
    May 3, 2016 at 9:27
  • @bravokeyl Ideally all past/future links. I am thinking that by using a filter within my functions, this will take care of all links old and new.
    – Glen
    May 3, 2016 at 9:32
  • You can use get_page_by_path to get the id from the slug ( We can get slug by parsing the link )
    – bravokeyl
    May 3, 2016 at 9:38

1 Answer 1

1

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);
}
2
  • I think this is not the answer for which you got upvotes on question ;)
    – Sumit
    May 3, 2016 at 11:31
  • It returns the ID's which is what I wanted, it's just a different approach
    – Glen
    May 3, 2016 at 11:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.