简体   繁体   中英

If statement using php and advances custom fields in wordpress - hide empty fields

I have an and if statement for a button.

If both advanced custom fields are present I want it to show the button and if not I want it to hide but I am struggling here.

I have looked at this page:

https://www.advancedcustomfields.com/resources/hiding-empty-fields/

Here is my code:

<?php if( get_field('button_link') && get_field('button_text') ): ?>
    <a href="<?php the_field('button_link');  ?>" class="btn third-btn mx-auto">
    <?php the_field('button_text');?> <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>
  </a>
<?php endif; ?>

Anyone got a suggestion please?

Cheers :)

I am not an ACF expert but looking at the get_field() function description here https://www.advancedcustomfields.com/resources/get_field/ it looks like the function will never return a boolean as mentioned on the Description and I quote:

Returns the value of the specified field

Since it does not return a boolean value, you can't assure get_field( 'something' ) && get_field( 'something2' ) will be the correct boolean. There are certain values that the if statement interpret as boolean true or false. For example null and 0 are interpreted as false, but -1 interpreted as true. I would recommend to do a

var_dump( get_field('button_link') ) 

to explore the output. Also, according to https://www.advancedcustomfields.com/resources/get_field/ under 'Check if value exists' you can check if one value exists, so this might work:

<?php if ( get_field( 'button_link' ) ) : ?>
    <?php if ( get_field( 'button_text' ) ) : ?>
        <a href="<?php the_field( 'button_link' ) ?>" class="btn third-btn mx-auto">
            <?php the_field( 'button_text' ) ?> <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>
        </a>
    <?php endif ?>
<?php endif ?>

It is like a nested AND without using the && operator. If this does not work we need more information about what you get from:

var_dump( get_field( 'button_link' ) );
var_dump( get_field( 'button_text' ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM