Ternary Operator for Advanced Custom Fields

I have been creating my own WP themes using Advanced Custom Fields extensively and I continue to type code out like:

<?php
if(get_field('featured_courses_heading_text', 'option')) {
    echo get_field('featured_courses_heading_text', 'option');
}
?>

Is there a more condensed version of this code I could use with Ternary Operators? I tried looking at the documentation but couldnt find anything

Related posts

2 comments

  1. You could just do this which will do the same thing, since you have no alternate value to output.

    <?php echo get_field('featured_courses_heading_text', 'option'); ?> 
    

    But if you were doing an if else then you could do this which will output the value if it doesn’t evaluate to nothing (false) null, <empty string>, 0, false

    <?php echo get_field('featured_courses_heading_text', 'option') ?: 'nothing here'; ?>
    

    Would be the same as

    <?php if(get_field('featured_courses_heading_text', 'option')) { echo get_field('featured_courses_heading_text', 'option'); } else { echo 'nothing here'; }  ?>
    
  2. I am not sure why you need a Ternary Operator; I think your code is fine.

    <?php 
        echo get_field('featured_courses_heading_text', 'option') ?: '';
    ?>
    

Comments are closed.