Search code examples
phpwordpressadvanced-custom-fields

Wordpress and ACF - How to echo an element if ACF value is set


<?php 
if ($a > $b):
    echo <li>Released: <?php the_field('date_released'); ?></li>
    echo <li>title: <?php the_field('title'); ?></li>
    echo <li>age: <?php the_field('age'); ?></li>
else if ($a == $b): 
    echo "Nothing";
endif;

This is the PHP code I have in WP. How can I echo the <li> element only if the ACF field has a value?


Solution

  • You want to use get_field() instead of the_field(). get_field returns the value, the_field() echoes the data, so you want to use get_field() to check if the data exists first.

    In this example I'm setting the field to a variable and then using an ternary operator to check if there is a value, echo that, if not, echo nothing.

    EDIT

    this removes the $a and $b variables:

    <?php
    $data_released = get_field( 'date_released' );
    $title         = get_field( 'title' );
    $age           = get_field( 'age' );
    
    // if the variable has a value, echo the <li>, if not, echo nothing.
    echo $data_released ? '<li>Released:' . $data_released . '</li>' : '';
    echo $title ? '<li>Title:' . $title . '</li>' : '';
    echo $age ? '<li>Age:' . $age . '</li>' : '';
    
    <?php
    $data_released = get_field( 'date_released' );
    $title         = get_field( 'title' );
    $age           = get_field( 'age' );
    
    if ( $a > $b ) :
        // if the variable has a value, echo the <li>, if not, echo nothing.
        echo $data_released ? '<li>Released:' . $data_released . '</li>' : '';
        echo $title ? '<li>Title:' . $title . '</li>' : '';
        echo $age ? '<li>Age:' . $age . '</li>' : '';
    elseif ( $a === $b ):
        echo 'Nothing';
    endif;
    
    A more verbose answer

    This does the same thing, but uses explicit if statements.

    <?php
    $data_released = get_field( 'date_released' );
    $title         = get_field( 'title' );
    $age           = get_field( 'age' );
    
    if ( $a > $b ) :
        // If the variable does not equal an empty string
        if ( $data_released !== '' ) :
            echo '<li>Released:' . $data_released . '</li>';
        endif;
        if ( $title !== '' ) :
            echo '<li>Title:' . $title . '</li>';
        endif;
        if ( $age !== '' ) :
            echo '<li>Age:' . $age . '</li>';
        endif;
    elseif ( $a === $b ):
        echo 'Nothing';
    endif;