0

I’ve created a Custom Post Type, “Slide”, and I’m attempting to load a random slide image, with title and caption, in my sidebar. I’m using the Advanced Custom Fields Plugin for the post/slide creation. The code below is what I have in my sidebar.php – I do get a random post loaded in the sidebar (showing title and caption) but the image URL does not output/echo, just <img src="" />

Can anyone tell if I have 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; ?>
4
  • Your code looks fine. Are you sure get_field('slide_photo') returns an image ID as opposed to an object or url. What do you get when you var_dump $attachment_id? What do you get when you var_dump $image?
    – patnz
    Jan 13 '14 at 23:21
  • Yes, forgot to mention, I have the slide_photo field set to image ID, not object or URL.
    – codeview
    Jan 13 '14 at 23:29
  • var_dump ($attachment_id); outputs: string(58) "path- to-image". 58 being the post id and path-to-image is the full path on my site.
    – codeview
    Jan 13 '14 at 23:40
  • var_dump ($image); outputs: bool(false)
    – codeview
    Jan 13 '14 at 23:42
0

You aren't getting an image because you are calling the image field outside the query loop.

<?php $args = array( 
    'post_type' => 'slide', 
    'posts_per_page' => 1, 
    'orderby' => rand
);

// url = $image[0];
// width = $image[1];
// height = $image[2];

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
    $attachment_id = get_field('slide_photo');
    $size = "medium"; // (thumbnail, medium, large, full or custom size)
    $image = wp_get_attachment_image_src( $attachment_id, $size );

    echo '<img src="';
    echo $image[0];
    echo '" />';
    the_title();
    the_field('slide_credit');

endwhile; ?>
2
  • Hmmm...tried that to no avail. Still no image url output :(
    – codeview
    Jan 13 '14 at 23:39
  • 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).
    – codeview
    Jan 14 '14 at 0:55

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.