WordPress added the function attachment_url_to_postid($url)
in version WP version 4.0.0.
This snippet is great, but if you need to find the ID from the URL that includes the cropped attributes, then you may need to add this snippet to your WordPress theme’s functions.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function get_attachment_id_by_url( $url ) { $post_id = attachment_url_to_postid( $url ); if ( ! $id ){ $dir = wp_upload_dir(); $path = $url; if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) { $path = substr( $path, strlen( $dir['baseurl'] . '/' ) ); } if ( preg_match( '/^(.*)(\-\d*x\d*)(\.\w{1,})/i', $path, $matches ) ){ $url = $dir['baseurl'] . '/' . $matches[1] . $matches[3]; $post_id = attachment_url_to_postid( $url ); } } return (int) $post_id; } |