Home > Enterprise >  php inside of html echo
php inside of html echo

Time:10-20

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  style="background: url('.$url.')">
                <div >
                    <span >' .$availability. '</span>
                    'if( get_field('delivery_date') ):' <span >' .$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.

CodePudding user response:

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  style="background: url('.$url.')">
                <div >
                    <span >' .$availability. '</span>';

    if( get_field('delivery_date') ): 
        echo '<span >' .$delivery_date. '</span>';
    endif;
    echo '</div>
      </div>
    </a>';
}
?>
  • Related