I’ve created a Custom Post Type, “Slide”, and I’m attempting to load a random slide image, with caption, in my sidebar. I’m using the ACF Plugin for the post/slide creation. The code below is what I have in my sidebar.php – I get a random post loaded in the sidebar (showing Title and Caption) but the image URL does not output/echo, just <img src="" />
.
Do I look to have the ACF code wrong or maybe using the WP_Query wrong?
<?php $args = array(
'post_type' => 'slide',
'posts_per_page' => 1,
'orderby' => rand
);
$attachment_id = get_field('slide_photo');
$size = "medium"; // (thumbnail, medium, large, full or custom size)
$image = wp_get_attachment_image_src( $attachment_id, $size );
// url = $image[0];
// width = $image[1];
// height = $image[2];
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<img src="';
echo $image[0];
echo '" />';
the_title();
the_field('slide_credit');
endwhile; ?>
Try moving this code
$attachment_id = get_field('slide_photo');
$size = "medium"; // (thumbnail, medium, large, full or custom size)
$image = wp_get_attachment_image_src( $attachment_id, $size );
into your loop. Outside of the loop, there’s no way to know what get_field('slide_photo')
is referring to.
Thanks for the quick reply, Will. I should have mentioned that I tried that to no avail. And also I do have the slide_photo image field set to Image ID, not URL or Object.
Doh! Looks like in troubleshooting I had actually changed the return value from “ID” to “URL”. All is working now (with moving the code as you suggested, which I had tried before, but after having changed the return value and forgetting).