This is my array of image URL's added to the same custom field named images.

   $images = get_post_custom_values( 'images' );

I need to print all these images in a template file.

  • Use $wpdb. get the IDs from a query on the posts table using guid = (the image URL). Depending on the URL you may have to factor in ###-### thumbnail sizing in URL. – David Sword Dec 16 '17 at 21:35

Since you are storing an url for each image you can create a query to get the id of the attachment based on the guid:

global $wpdb;
$ids = array();
foreach ($images as $image_url) {
  $ids[] = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url));

Another way would be to simply store the ID rather than the url in your custom field, then there would not be necessary to perform a the above query for each image.

  • Thanks, i like your 2nd option however this can only be done by grabbing the image I.D and adding it manually to each custom field unless i use a plugin like ACF. – Dev Dec 17 '17 at 8:20
  • I'll give you a upvote for this however its not something which i be using. – Dev Dec 17 '17 at 9:11
  • @Dev - Regarding you first comment, you should be able to use the save_post action then when a post i saved/updated you check you custom fields and if they contains a url you grab the corresponding ID as in the above example and update the field with this id rather than storing the url. It would be interesting if you could tell me how you solved this if you are not using code as in my answer? – Cyclonecode Dec 17 '17 at 11:13
  • 1
    Thanks. I actually ended up using get_post_custom_values which was a lot easier to work with using the URL's rather than I.D's. – Dev Dec 17 '17 at 11:46

This is how i ended up coding the solution :

$images = get_post_custom_values( 'images' );

if ( $images ) {

    echo '<div class="image-wrap">';

    if ( $image_header ) {
        echo '<div class="header">' . esc_html( $image_header ) . '</div>';

    foreach ( (array) $images as $image ) {

        $url = esc_url( $image );
        $alt = esc_html( the_title_attribute( 'echo=0' ) );

        if ( $url ) {
            echo '<img class="image-section" src="' . $url . '" alt="' . $alt . '" />';


    echo '</div>';


To get the i.d from a URL

You can use attachment_url_to_postid like this :

$url          = 'http://example.com/img.png';
$id           = attachment_url_to_postid( $url );
$alt          = get_post_meta( $id, '_wp_attachment_image_alt', true );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.