Skip to content

Commit

Permalink
add new template tag: get attachment ID from it's URL
Browse files Browse the repository at this point in the history
  • Loading branch information
gregrickaby committed Oct 14, 2015
1 parent 57abfff commit 3db68bd
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions inc/template-tags.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,40 @@ function _s_get_post_image_uri( $size = 'thumbnail' ) {

return $media_url;
}

/**
* Get an attachment ID from it's URL.
*
* @param string $attachment_url The URL of the attachment.
* @return int The attachment ID.
*/
function _s_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;
}

0 comments on commit 3db68bd

Please sign in to comment.