Home > database >  How to add if else in ACF
How to add if else in ACF

Time:05-29

<?php
$featured_posts = get_field('director');
if( $featured_posts ): ?>
    <ul>
    <?php foreach( $featured_posts as $featured_post ):?>
      
        <div >
                <a  href="<?php echo get_page_link($featured_post->ID);?>"> <img src="<?php echo get_the_post_thumbnail_url($featured_post->ID, 'thumbnail');?>"></a>
            <div >
                <h4>  <a href="<?php echo get_page_link($featured_post->ID);?>"> <?php echo $featured_post->post_title;?> </a> </h4> 
                <b>Director</b>
            </div>               
        </div>
       
    <?php endforeach; ?>
    </ul>
<?php endif; ?>

Guys how to output like this.

If has thumbnail then post thumbanil else if no thumnail then print this this image (no image)

CodePudding user response:

You want to check if the thumbnail is empty, and if there is no thumbnail, display a default image.

So you use get_the_post_thumbnail_url() and check if it is empty.

if ( empty(get_the_post_thumbnail_url( $featured_post->ID)) ):
    echo 'https://your-default-image_url.jpg';
else:
    echo get_the_post_thumbnail_url( $featured_post->ID, 'thumbnail' );
endif;

If you like it a bit more readable, your code can look like:

<ul>
<?php foreach( $featured_posts as $featured_post ):?>
    <?php $featured_image = get_the_post_thumbnail_url($featured_post->ID, 'thumbnail') ?: 'https://your-default-image_url.jpg'; ?>
  
    <div >
            <a  href="<?php echo get_page_link($featured_post->ID);?>"> <img src="<?php echo $featured_image;?>"></a>
        <div >
            <h4>  <a href="<?php echo get_page_link($featured_post->ID);?>"> <?php echo $featured_post->post_title;?> </a> </h4> 
            <b>Director</b>
        </div>               
    </div>
   
<?php endforeach; ?>
</ul>

CodePudding user response:

Here is your working code:


<?php
$featured_posts = get_field('director');
if( $featured_posts ): ?>
    <ul>
    <?php foreach( $featured_posts as $featured_post ):?>
      
        <div >
                <a  href="<?php echo get_page_link($featured_post->ID);?>"> <img src="<?php echo get_the_post_thumbnail_url($featured_post->ID, 'thumbnail');?>"></a>
            <div >
                <h4>  <a href="<?php echo get_page_link($featured_post->ID);?>"> <?php echo $featured_post->post_title;?> </a> </h4> 
                <b>Director</b>
            </div>               
        </div>
       
    <?php endforeach; ?>
    </ul>
<?php else: ?>
    .... here your code for "else"
<?php endif; ?>
  • Related