0
votes

I am trying to get an image URL with attachment size using an advanced custom field. The field is set to ID. I've used this approach to get other images by ID with no problem. Yet this one isn't pulling the rendered image. It's pulling the ID number and displaying it on the page. I'm stumped...

<?php
$the_query = new WP_Query( array(
    'post_type' => 'listicles',
    'tax_query' => array(
        array (
        'taxonomy' => 'visibility',
        'field'    => 'slug',
        'terms' => 'listicles-resortsvisible',
        ),
    ),
) ); 
    $listicleimage = the_field('listicle_featured_image', $post->ID);
    $listicleimgsize = 'listicle-thumb';
    $listicleimg_array = wp_get_attachment_image_src($listicleimage, $listicleimgsize);
    $listicleimg_url = $listicleimg_array[0];
?>

<ul
class="row small-up-1 medium-up-2">

<?php if ( $the_query->have_posts() ) : ?>

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>


<li class="small-12 medium-6 column">


<img
    src="<?php echo  $listicleimg_url; ?>"
    class="align-center" />

//THE REST OF MY CONTENT//

</li>
<?php endwhile;?>
<?php endif; ?>
</ul>

<?php wp_reset_query(); ?>
3

3 Answers

0
votes

You only need to change

the_field('listicle_featured_image', $post->ID);

to

get_field('listicle_featured_image', $post->ID);
0
votes

You should be using wp_get_attachment_image and not wp_get_attachment_image_src.

wp_get_attachment_image accepts ID's as an argument.

Source: https://developer.wordpress.org/reference/functions/wp_get_attachment_image/

0
votes

Add this to functions.php

function img_by_id($id, $size, $url) {
        $the_img = wp_get_attachment_image($id, $size);
        if ($url != true) {
            return $the_img;
        }
        else {
            $img_src = get_attr($the_img, 'src');
            return $img_src;
        }
    }

function get_attr($html, $attr) {
    $pc = explode($attr.'="', $html);
    $pc2 = explode('"', $pc[1]);
    return $pc2[0];
}

Then

<?php
    $the_query = new WP_Query( array(
        'post_type' => 'listicles',
        'tax_query' => array(
            array (
            'taxonomy' => 'visibility',
            'field'    => 'slug',
            'terms' => 'listicles-resortsvisible',
            ),
        ),
    ) ); 
    $listicleimage = the_field('listicle_featured_image', $post->ID);
    $listicleimg_url = img_by_id( $listicleimage, 'listicle-thumb', true);

?>

if you need full image attribute with sizes $img = img_by_id( $listicleimage, 'listicle-thumb', false); If you need specific attribute from html tag $attr = get_attr($html, $attr);

I have this on my blank WP theme template.