phpwordpresswordpress-media

How to get the attachment id from the attachment page url?


I'm trying to get the id of the attachment from the attachment page url.

When creating a custom post, I uploaded media to the post.

The media now has an attachment page - http://localhost/site/custom-post/post-name/screenshot_20211005-091742/

How can I get the attachment id from this url? I've tried the attachment_url_to_postid function but this appears to only work for the direct media url e.g. http://localhost/site/wp-content/uploads/2021/10/Screenshot_20211005-091742.png

I've also tested for media uploaded directly to the media library http://localhost/site/wp-content/uploads/2021/10/S036662860_0.jpg but attachment_url_to_postid returns 0.

enter image description here


Solution

  • You could use the url_to_postid instead of attachment_url_to_postid, localhost/site/custom-post/post-name/screenshot_20211005-091742/ is a page URL, not a direct file URL.