Categories
Development PHP Plugins Themes WordPress

New in WordPress 3.6: the attachment_url_to_postid() Function

If you’re writing a WordPress plugin, you may have a scenario where you have an attachment (file) URL, and you’d like to obtain the associated post (attachment) ID.

Luckily, this is very easy to do in WordPress 3.6 because of the new attachment_url_to_postid() function.

The function’s syntax is simple – you pass it a string (the file URL), and it returns an integer (the associated post id), or zero on failure.

Here’s a simple example:

As mentioned above, this function is available in WordPress 3.6 – it will cause a fatal error if you try to use it in any earlier versions such as WordPress 3.5.x.

Thanks to Zack Tollman for the heads up about this handy new function.