1

I am having some trouble trying to add an if statement to hide an ACF field inside of an HTML echo.

<?php
$link = get_permalink();
$availability = get_field('availability');
$delivery_date = get_field('delivery_date');
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
if ( has_post_thumbnail() ) {
    echo '<a href="' .$link. '">
            <div class="thumbnail" style="background: url('.$url.')">
                <div class="tags one">
                    <span class="availability">' .$availability. '</span>
                    'if( get_field('delivery_date') ):' <span class="delivery-date">' .$delivery_date. '</span> 'endif;'
                </div>
            </div>
        </a>';
    }
?>

Please would someone be able to advise on where I'm going wrong with the if statement to hide the field if it's empty? At the moment it just errors the page.

4
  • At the moment it just errors the page. So it would be useful if you showed us the error Commented Oct 20, 2022 at 13:55
  • The page stops displaying the content. There is no specific error. I assume to code I have applied for the if statement in the echo is incorrect. Commented Oct 20, 2022 at 13:57
  • you can't just drop an if statement in the middle of an echoed string. Commented Oct 20, 2022 at 14:05
  • Ah, that makes a lot of sense now you've mentioned it. I'm still new to all this if you can't tell. Commented Oct 20, 2022 at 14:14

1 Answer 1

1

Break the PHP code out of the text string, this is one way

<?php
$link = get_permalink();
$availability = get_field('availability');
$delivery_date = get_field('delivery_date');
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
if ( has_post_thumbnail() ) {
    echo '<a href="' .$link. '">
            <div class="thumbnail" style="background: url('.$url.')">
                <div class="tags one">
                    <span class="availability">' .$availability. '</span>';

    if( get_field('delivery_date') ): 
        echo '<span class="delivery-date">' .$delivery_date. '</span>';
    endif;
    echo '</div>
      </div>
    </a>';
}
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.