Skip to content

Instantly share code, notes, and snippets.

@soderlind
Last active December 30, 2015 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soderlind/7791628 to your computer and use it in GitHub Desktop.
Save soderlind/7791628 to your computer and use it in GitHub Desktop.
WordPress: Get image id from WordPress post. Images first added to the media uploader and then added to a post aren't attached i.e. you can't use $attachments = get_posts( array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'inherit', 'post_parent' => $post->ID));
<?php
// you need to add the post content to $post_content
preg_match_all('/src=([\'"])?((?(1).*?|\S+))(?(1)\1)/', $post_content, $images);
if (count($images[2]) > 0) {
foreach ($images[2] as $src) {
$image_id = pn_get_attachment_id_from_url($src);
/*
Do something with the $image_id
*/
}
}
// from: http://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/
function pn_get_attachment_id_from_url( $attachment_url = '' ) {
global $wpdb;
$attachment_id = false;
// If there is no url, return.
if ( '' == $attachment_url )
return;
// Get the upload directory paths
$upload_dir_paths = wp_upload_dir();
// Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
if ( false !== strpos( $attachment_url, $upload_dir_paths['baseurl'] ) ) {
// If this is the URL of an auto-generated thumbnail, get the URL of the original image
$attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url );
// Remove the upload path base directory from the attachment URL
$attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );
// Finally, run a custom database query to get the attachment ID from the modified attachment URL
$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url ) );
}
return $attachment_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment