attachment_url_to_postid

Tries to convert an attachment URL into a post ID.

Description

(int) attachment_url_to_postid( (string) $url ); 

Returns (int)

The found post ID, or 0 on failure.

Parameters (1)

0. $url (string)
The URL to resolve.

Usage

  1. if ( !function_exists( 'attachment_url_to_postid' ) ) { 
  2. require_once ABSPATH . WPINC . '/media.php'; 
  3.  
  4. // The URL to resolve. 
  5. $url = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = attachment_url_to_postid($url); 
  9.  

Defined (1)

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

/wp-includes/media.php  
  1. function attachment_url_to_postid( $url ) { 
  2. global $wpdb; 
  3.  
  4. $dir = wp_get_upload_dir(); 
  5. $path = $url; 
  6.  
  7. $site_url = parse_url( $dir['url'] ); 
  8. $image_path = parse_url( $path ); 
  9.  
  10. //force the protocols to match if needed 
  11. if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) { 
  12. $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path ); 
  13.  
  14. if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) { 
  15. $path = substr( $path, strlen( $dir['baseurl'] . '/' ) ); 
  16.  
  17. $sql = $wpdb->prepare( 
  18. "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",  
  19. $path 
  20. ); 
  21. $post_id = $wpdb->get_var( $sql ); 
  22.  
  23. /** 
  24. * Filters an attachment id found by URL. 
  25. * @since 4.2.0 
  26. * @param int|null $post_id The post_id (if any) found by the function. 
  27. * @param string $url The URL being looked up. 
  28. */ 
  29. return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );