Skip to content

Instantly share code, notes, and snippets.

@nicolabavaro
Created September 7, 2018 08:46
Show Gist options
  • Save nicolabavaro/59e9a638b58a539aa2e477117fe0d78a to your computer and use it in GitHub Desktop.
Save nicolabavaro/59e9a638b58a539aa2e477117fe0d78a to your computer and use it in GitHub Desktop.
Wordpress: Get attachment ID from attachment url
/**
* Ottengo l'ID di un attachment attraverso il suo URL
*
* @param $url
* @return int
*/
public function get_attachment_id( $url )
{
$attachment_id = 0;
$dir = wp_upload_dir();
if (false !== strpos($url, $dir['baseurl'] . '/')) { // Is URL in uploads directory?
$file = basename($url);
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
'key' => '_wp_attachment_metadata',
),
)
);
$query = new WP_Query($query_args);
if ($query->have_posts()) {
foreach ($query->posts as $post_id) {
$meta = wp_get_attachment_metadata($post_id);
$original_file = basename($meta['file']);
$cropped_image_files = wp_list_pluck($meta['sizes'], 'file');
if ($original_file === $file || in_array($file, $cropped_image_files)) {
$attachment_id = $post_id;
break;
}
}
}
}
return $attachment_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment