videopress_get_attachment_id_by_url

Get an attachment ID given a URL.

Description

(int|bool) videopress_get_attachment_id_by_url( (string) $url ); 

Modified from http://wpscholar.com/blog/get-attachment-id-from-wp-image-url/

Returns (int|bool)

Attachment ID on success, false on failure

Parameters (1)

0. $url (string)
The url.

Usage

  1. if ( !function_exists( 'videopress_get_attachment_id_by_url' ) ) { 
  2. require_once '/modules/videopress/utility-functions.php'; 
  3.  
  4. // The url. 
  5. $url = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = videopress_get_attachment_id_by_url($url); 
  9.  

Defined (1)

The function is defined in the following location(s).

/modules/videopress/utility-functions.php  
  1. function videopress_get_attachment_id_by_url( $url ) { 
  2. $wp_upload_dir = wp_upload_dir(); 
  3. // Strip out protocols, so it doesn't fail because searching for http: in https: dir. 
  4. $dir = set_url_scheme( trailingslashit( $wp_upload_dir['baseurl'] ), 'relative' ); 
  5.  
  6. // Is URL in uploads directory? 
  7. if ( false !== strpos( $url, $dir ) ) { 
  8.  
  9. $file = basename( $url ); 
  10.  
  11. $query_args = array( 
  12. 'post_type' => 'attachment',  
  13. 'post_status' => 'inherit',  
  14. 'fields' => 'ids',  
  15. 'meta_query' => array( 
  16. array( 
  17. 'key' => '_wp_attachment_metadata',  
  18. 'compare' => 'LIKE',  
  19. 'value' => $file,  
  20. ),  
  21. ); 
  22.  
  23. $query = new WP_Query( $query_args ); 
  24.  
  25. if ( $query->have_posts() ) { 
  26. foreach ( $query->posts as $attachment_id ) { 
  27. $meta = wp_get_attachment_metadata( $attachment_id ); 
  28. $original_file = basename( $meta['file'] ); 
  29. $cropped_files = wp_list_pluck( $meta['sizes'], 'file' ); 
  30.  
  31. if ( $original_file === $file || in_array( $file, $cropped_files ) ) { 
  32. return (int) $attachment_id; 
  33.  
  34.  
  35. return false;