Zerion
Zerion

Reputation: 51

Struggling to show image with ACF WordPress

I've been trying to display an image with ACF code and have just got it working, but I can't work out why some code works and some doesn't.

if(get_row_layout() == 'bq_product'):
        $image = the_sub_field('affiliate_image');
        $affiliate_url = the_sub_field('affiliate_url');
                
        
        ?><img src="<?php echo $image ?>"/><?php //This line doesn't work and just displays the raw URL on the front end
        ?><img src="<?php the_sub_field('affiliate_image') ?>"/><?php //This line works and shows the image
        ?><a href="<?php $affiliate_url ?>">Link</a> //Similarly, this line doesn't use the URL set in affiliate_url, but does if I pass "the_sub_field('affiliate_url')"

How do I use the variable names within the image src without it just showing the raw URL on the front end?

I've tried using "get_sub_field" variations but they don't seem to make a difference.

Upvotes: 0

Views: 379

Answers (1)

joshmoto
joshmoto

Reputation: 5128

Exactly as @Stender commented, attempting to store variables using ACF the_sub_field() will not work.

Use get_sub_field() instead to store returned ACF field data to your variables.

Then access variable data based on what you have set the ACF fields to return with... array, ID or URL

  1. See example below (based on affiliate_image ACF field return format URL)
// if row layout is 'bq_product'
if(get_row_layout() == 'bq_product'):
 
    // sub field vars
    $affiliate_image  = get_sub_field('affiliate_image');
    $affiliate_url    = get_sub_field('affiliate_url');
                
    // if $affiliate_image variable is not boolean false    
    if($image) {
        echo '<img src="' . $affiliate_image . '" alt="" />';
    }

    // if $affiliate_url is not boolean false
    if($affiliate_url) {
        echo '<a href="' . $affiliate_url . '">Link</a>';
    }

endif;  
  1. See example below (based on affiliate_image ACF field return format array)
// if row layout is 'bq_product'
if(get_row_layout() == 'bq_product'):
 
    // sub field vars
    $affiliate_image  = get_sub_field('affiliate_image');
    $affiliate_url    = get_sub_field('affiliate_url');

    // use this to dump $affiliate_image array to see data for image sizes etc
    // echo '<pre>' . print_r($affiliate_image, true) . '</pre>';
         
    // if $affiliate_image variable is array       
    if(is_array($affiliate_image) {
        echo '<img src="' . $affiliate_image['url'] . '" alt="' . $affiliate_image['alt'] . '" />';
    }

    // if $affiliate_url is not boolean false
    if($affiliate_url) {
        echo '<a href="' . $affiliate_url . '">Link</a>';
    }

endif;  

Upvotes: 1

Related Questions