Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attachment ID by file path in WordPress

Tags:

wordpress

I know the path of the file and I like to get the attachment ID.

There's a function wp_get_attachment_url() which requires the ID to get the URL but I need it reverse (with path not URL though)

like image 596
Xaver Avatar asked Sep 04 '14 16:09

Xaver


People also ask

How do I find the file path in WordPress?

You can use a WordPress function of plugin_dir_path() to get the full path of the folder. include_once plugin_dir_path( __FILE__ ) . 'new-file.

What is _wp_attached_file?

The function works by getting the single post meta name, named '_wp_attached_file' and returning it. This is a convenience function to prevent looking up the meta name and provide a mechanism for sending the attached filename through a filter.


1 Answers

UPDATE: since wp 4.0.0 there's a new function that could do the job. I didn't tested it yet, but it's this:

https://developer.wordpress.org/reference/functions/attachment_url_to_postid/


OLD ANSWER: so far, the best solution I've found out there, is the following:

https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/

I think It's the best for 2 reasons:

  • It does some integrity checks
  • [important!] it's domain-agnostic. This makes for safe site moving. To me, this is a key feature.
like image 120
Luca Reghellin Avatar answered Oct 27 '22 01:10

Luca Reghellin