I've got a product custom post type that can have a user supplied image, or a default image.
My code currently only pulls in the default image. I need it to use the user supplied image field if available, else fall back to the default.
In the code below, the 'main_image_link' ACF field is the default.
<?php
$loop = new WP_Query(
array(
'post_type' => 'oils-blends',
'meta_key' => 'type',
'meta_value' => 'diffuser',
'meta_compare' => 'LIKE',
'orderby'=>'title',
'order'=>'ASC',
'posts_per_page' => 40
)
);
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="oil-products-container" itemscope itemtype="http://schema.org/Product">';
echo '<div class="oil-products-image"><a href="';
the_permalink();
echo '"><img src="';
the_field('main_image_link');
echo '" alt="';
the_title();
echo '"></a></div>';
echo '<div class="oil-products-title"><a href="';
the_permalink();
echo '" class="black-link"><span itemprop="name">';
the_field('short_name');
echo '</span></a></div></div>';
endwhile;
?>
<?php endwhile; ?>
Thanks!
Arnav Joy answers:
Please try this solution
<?php
$loop = new WP_Query(
array(
'post_type' => 'oils-blends',
'meta_key' => 'type',
'meta_value' => 'diffuser',
'meta_compare' => 'LIKE',
'orderby'=>'title',
'order'=>'ASC',
'posts_per_page' => 40
)
);
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="oil-products-container" itemscope itemtype="http://schema.org/Product">';
echo '<div class="oil-products-image"><a href="';
the_permalink();
echo '"><img src="';
if( get_field('user_supplied_image') )
the_field('user_supplied_image');
else
the_field('main_image_link');
echo '" alt="';
the_title();
echo '"></a></div>';
echo '<div class="oil-products-title"><a href="';
the_permalink();
echo '" class="black-link"><span itemprop="name">';
the_field('short_name');
echo '</span></a></div></div>';
endwhile;
?>
<?php endwhile; ?>
the main code is this
if( get_field('user_supplied_image') )
the_field('user_supplied_image');
else
the_field('main_image_link');
Please note that you have to change "user_supplied_image" key above and have to use correct key which is used for user supplied image
Kyler Boudreau comments:
Arnav,
Beautiful - your code worked. Thank you!!!
Romel Apuya answers:
whats the field name of the user supplied image?
Romel Apuya comments:
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="oil-products-container" itemscope itemtype="http://schema.org/Product">';
echo '<div class="oil-products-image"><a href="';
the_permalink();
echo '">
if ( has_post_thumbnail() ){
the_post_thumbnail();
}else{
<img src="';
the_field('main_image_link');
echo '" alt="';
the_title();
echo '">
}
</a></div>';
echo '<div class="oil-products-title"><a href="';
the_permalink();
echo '" class="black-link"><span itemprop="name">';
the_field('short_name');
echo '</span></a></div></div>';
endwhile;