如果语句使用 php 并在 wordpress 中推进自定义字段 - 隐藏空字段

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

我有一个按钮的 and if 语句。

如果两个高级自定义字段都存在,我希望它显示按钮,如果没有,我希望它隐藏,但我在这里很挣扎。

我看过这个页面:

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

这是我的代码:

<?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; ?>

有人有什么建议吗?

干杯:)

我不是 ACF 专家,但在此处查看 get_field() 函数描述 https://www.advancedcustomfields.com/resources/get_field/ 看起来该函数永远不会 return 描述中提到的布尔值和我引用:

Returns the value of the specified field

因为它不是 return 布尔值,你不能保证 get_field( 'something' ) && get_field( 'something2' ) 会是正确的布尔值。 if 语句将某些值解释为布尔值 true 或 false。例如,null 和 0 被解释为 false,而 -1 被解释为 true。我建议做一个

var_dump( get_field('button_link') ) 

探索输出。此外,根据 'Check if value exists' 下的 https://www.advancedcustomfields.com/resources/get_field/,您可以检查一个值是否存在,因此这可能有效:

<?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 ?>

就像不使用 && 运算符的嵌套 AND。如果这不起作用,我们需要更多关于您从中获得的信息:

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