How do I show the post title if an advanced custom field hasn't been used?

I've got an archive page for to display custom post types.

Within the WP_Query that displays the custom posts types I want to display an ACF (Advanced Custom Field) or, if the user hasn't filled out the ACF, then the title should appear.

I've tried this and the ACF field displays ok, but when it's not filled out, the title doesn't display, just the content of the post instead.

Here's the code I have (just for the title section):

?php $loop = new WP_Query( array( 'post_type' = 'project', 'posts_per_page' = -1, 'orderby' = 'menu_order' ) ); ?

?php while ( $loop-have_posts() ) : $loop-the_post(); ?
    div class="project col-md-4"
    div class="col-xs-12 short-testimonial"

        ?php if(get_field('short_testimonial')): ?

        ?php the_field('short_testimonial'); ?

        ?php else: ?

        ?php echo the_title(); ?

        ?php endif; ?

    /div

Topic advanced-custom-fields title loop wp-query posts Wordpress

Category Web


You should try removing "echo" from "the_title()".

This should work

<div class="project col-md-4">
     <div class="col-xs-12 short-testimonial">
          <?php 
               if( get_field( 'short_testimonial' ) ): 
               the_field( 'short_testimonial' );
               else:
               the_title();
               endif;
          ?>    
     </div>
</div>

You could also look at the official documentation here.

You will notice that the_title already displays it by default.

<?php the_title( $before, $after, $echo ); ?>

If in doubt, check the documentation first: https://www.advancedcustomfields.com/resources/get_field/

Check if value exists

This example shows how to check if a value exists for a field.

$value = get_field( 'text_field' );

if ( $value ) {
    echo $value;
} else {
    echo 'empty';
}

So, in for your case you would need to use:

<?php

$short_testimonial = get_field( 'short_testimonial' );

if ( $short_testimonial ) {
    echo $short_testimonial;
} else {
    the_title();
}

?>

Also, you should note, as others have mentioned, that you don't need to echo the_title() as it echoes itself...

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.