Get link from post ID

I’m sure it’s super simple, but I cant figure out, how to get a working link to a post from a post ID?

Details: My CPT has an ACF Post Object field, what returns Post ID. I can get the ID with item.acf.post_link, but this does not work:

<Link link={item.acf.post_link ? item.acf.post_link : "/"}>
  <Html2React html={item.content.rendered} />

Hi @koli14! :wave:

Which variable in your code snippet is supposed to contain the post ID and which one is supposed to contain the link?

I can get the ID with item.acf.post_link , but this does not work:

Could you be more specific about what does not work? Does it throw an error? Is item.content.rendered undefined? Is it something else?

Also, have you followed the documentation on post types ?

The item.acf.post_link contains a Post ID. And I want to create a link based on that, and set the link attribute of the Link to that link. The rest of the code is working. Just the Link is not working, as item.acf.post_link is not a link, just a Post ID. And I do not know, how to create a link from that Post Id.

Okay, I see.

Well, the bad news is that you cannot just “get” the link for the post from the post ID. But the good news is that you can in most cases construct the link yourself :slightly_smiling_face:

Your CPT should contain another field called slug. Using the slug you can construct the link, like so:

  • If you have your WP configured to use /slug for posts, then it’s possible:

    • /slug ----> /normal-post-or-page

    but if you have custom post types, then it may be /cpt/slug So:

    • /cpt/slug ----> /products/some-product
  • If you are using the year/month, for example /year/month/slug then it’s going to be more complicated because you don’t know the year or month (acf doesn’t expose those I think) and you might have to change the WP settings then.

I hope this helps!


Thanks @mmczaplinski.
Then I need to set the ACF field to return the post_object, instead the Post ID, so it makes some extra traffic, as the post content comes also, but that’s life…

1 Like