0

I'm currently using get_field with Advanced Custom Fields plugin (see here) to get a single image for search results. The end result is that these pages are loading slow, as I believe this is due to MySQL returning the whole array of all images in the gallery for the specified page, which ends up being huge.

To load the image, I am currently doing the following:

$image = get_field('house_photos'); 

    if ($image) {

        echo '<img src="' . $image[0]['sizes']['house_search'] . '"  />'; 

    } 

Is there a more efficient way just to get this single image without requesting the entire array?

1
  • I don't have any test-cases of my own, but you are returning the image object compared to just returning the ID and then running it through WP functions like wp_get_attachment_image_src, so it may be something to consider (the image object is doing/returning more than you may need).
    – Zach
    Oct 9, 2012 at 14:14

3 Answers 3

2

I have managed to work it out - the function was leading to a lot of queries, so I rewrote it as follows:

    $housePhotos = get_post_custom_values('house_photos');

    $housePhotos = explode(';',$housePhotos[0]);

    preg_match_all('`"([^"]*)"`', $housePhotos[1], $results);

    $imageURL = wp_get_attachment_image_src( $results[1][0], 'house_search' );

    if (!empty($results[1][0])) {

        echo '<img src="' . $imageURL[0] .'" alt="" />'; 

    } 
0
0

In advanced custom value if you adding field choose field type "image" & choose return value "Image URL". To display image use

$image = get_field('house_photos'); 
    if ($image) {
        echo '<img src="' . $image . '"  />'; 
    }

If you return the ID, you'd use:

$image_id = get_field('house_photos');
$image_src = wp_get_attachment_image_src( $image_id, 'full');

if ($image_id) {
    echo '<img src="'.$image_src[0].'" width="'.$image_src[1].'" height="'.$image_src[2].'">';
}
1
  • The problem is with get_field() itself, when retrieving a gallery field. Having the same issue. Ollie's answer seems promising though.
    – Odys
    Nov 4, 2014 at 23:13
0

You coudld just use $housePhotos = get_post_meta( $post->ID, 'house_photos', true ) to get an array of the image id's. Then you could get the first image by saying $imageURL = wp_get_attachment_image_src( $housePhotos[0], 'house_search' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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