This code enables you to get the attachment i.d from any type of image URL.
In the following example, the code enables you to get the I.D from a image URL added to a custom field named image.
$url = get_post_meta( get_the_ID(), 'image', true );
$id = attachment_url_to_postid( $url );
Genesis users can swap out get_post_meta with genesis_get_custom_field.
Test The Code
To test the code returns the correct attachment i.d for the image, you can use the following snippet in your child themes functions.php file to output :
add_action( 'the_post', 'convert_attachment_url_to_postid' );
function convert_attachment_url_to_postid() {
$url = get_post_meta( get_the_ID(), 'image', true );
$id = attachment_url_to_postid( $url );
echo $id;
}
You could also get the i.d from a raw URL like this :
$url = 'http://test.dev/wp-content/uploads/2017/10/img.jpg';
$id = attachment_url_to_postid( $url );
Get I.D’s from array of URL’s
If you’ve added multiple image URL’s to the same custom field, you can use foreach with get_post_custom_values to get all the attachments i.d’s from a array like this :
$urls = get_post_custom_values( 'logos' );
foreach( (array) $urls as $url ) {
$id = attachment_url_to_postid( $url );
echo esc_html( $id );
}
Test The Code
And test the code like this :
add_action( 'wp_head', 'test_code' );
function test_code() {
$urls = get_post_custom_values( 'logos' );
foreach( (array) $urls as $url ) {
$id = attachment_url_to_postid( $url );
echo esc_html( $id );
}
}
This is a much more efficient method than using the global $wpdb;
object variable.
Leave a Reply