-1

I am trying to use a custom fields plugin to replace the featured image on a post. If the custom field is empty i want it to show the featured image, if the custom field has an image i want it to show that image.

<div class="showcase-pic">

            <?php $image = get_field('shown_image'); 

                if ( !empty($image) ): ?>

                <a href="<?php echo $image['url']; ?>"><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /></a><br />

                 <?php elseif (has_post_thumbnail( $post->ID ) ): ?>

                <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?> 

                <a href="<?php echo $image[0]; ?>"><img src="<?php echo $image[0]; ?>" alt=""></a>

               <?php endif; ?>

            </div><!--eof of show case pic -->
Zombo
  • 1
  • 62
  • 391
  • 407
John Garcia
  • 58
  • 1
  • 10

2 Answers2

1

Simplify your statement to an if/else (since your only looking for two outputs). If the image field has a value, use it. If it doesn't then use the featured image. And you only need to check if the image exists.

<?php $image = get_field('shown_image'); ?>
  <? if ( $image ) : ?>
    <img src="<?= $image['url'];?>"/>
  <?php else : ?>
    <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?> 
    <a href="<?php echo $image[0]; ?>"><img src="<?php echo $image[0]; ?>" alt=""></a>
  <?php endif;?>
cooper_hu
  • 21
  • 5
0

What error do you get?

Here are some steps you need to take to debug your code.

1) var_dump(get_field('shown_image')); -- This way you check if the get_field returns any data and what data it is.

2)If var_dump returns an object. You need to be sure that it has a url field in it and it is not empty

3)var_dump(has_post_thumbnail( $post->ID )); -- In order for your elseif statement to be true this function should return true. See what it returns

4)var_dump(wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID )) -- This is a complex invokation of functions. You need to be sure that both functions return something.

5)If the upper var_dump returns something then check if $image[0]; is not empty.

These are the basics of debuging. Try to debug step by step and do not debug the entire code. Because you might expect to have one error but in reality you may have dozens of erorrs.

SergeyAn
  • 754
  • 6
  • 9