How to turn an URL into an attachment ID?

How to turn an URL into an attachment ID?

All those complex functions can be reduced to one simple function: You only need to parse the image URL to retrieve the attachment ID: That’s all you need. I modified Rarst’s code to allow you to match just the filename instead of the full path. This is helpful if you are about to sideload the image if it does not exist.

How to get attachment ID by file path in WordPress?

Based on the answer from @FrancescoCarlucci I could do some improvements. Sometimes, for example when you edit an image in WordPress, it creates a copy from the original and adds the copys upload path as post meta (key _wp_attached_file) which is not respected by the answer. Thanks for contributing an answer to Stack Overflow!

How to convert url to post ID in WordPress?

Please check the this url for your reference. Since wordpress version 4.0 there is a wordpress core function attachment_url_to_postid that “Tries to convert an attachment URL into a post ID.” But these function has huge flaw cos it can’t convert custom image url sizes.

How to get attachment ID by file path?

Try attachment_url_to_postid function. None of the other answers here appear to work properly or reliably for a file path. The answer using Pippin’s function also is flawed, and doesn’t really do things “the WordPress Way”.

How to find the post ID of an url?

url_to_postid( string $url ) Examine a URL and try to determine the post ID it represents.

How to redirect attachment URLs to parent post URLs?

If you’re using Yoast’s SEO plugin, the solution is a doddle: simply navigate to ‘SEO’ → ‘Permalinks’ and check the ‘ Redirect attachment URLs to parent post URL ‘ checkbox — as shown in the following image: Problem solved (and yet another reason to use Yoast’s invaluable SEO Plugin)!

What to do with attachment URLs in WordPress?

There are few schools of thought on this: a) leave them be and don’t worry about them too much (hmmm), b) ask search engines to no-index them, or c) redirect them to the original post into which the media was inserted, which is what we do on this very site – with the help of Yoast’s incredibly-popular SEO Plugin: WordPress SEO by Yoast.