【问题标题】:If statement using php and advances custom fields in wordpress - hide empty fieldsIf语句使用php并在wordpress中推进自定义字段 - 隐藏空字段
【发布时间】:2017-06-05 17:46:30
【问题描述】:

我有一个按钮的 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; ?>

请问大家有什么建议吗?

干杯:)

【问题讨论】:

  • 我喜欢使用 get_post_meta() 代替,对我来说似乎更清楚,但在这里检查“值存在”选项:advancedcustomfields.com/resources/get_field - 您的 button_link 和 button_text 字段可能返回一个空数组或字符串,不是布尔值 false - 因此它会评估您的 if 块。
  • 需要填充链接和文本,才能使语句评估为真。您是说即使这些值为空,您的按钮也会呈现?我会调试该语句(xdebug、var_dump 或回显get_field('button_link')get_field('button_text') 的结果,因为它们必须包含一个真值(布尔真、非空字符串或正整数)。
  • 我发现你的代码没有问题,当 button_link 和 button_text 字段不为空时,它应该显示按钮,使用 print_r(get_filed('button_link'));和 print_r(get_filed('button_text'));看看他们是否有价值观
  • 感谢所有 cmets 人! Máximo 为我整理了 :) 干杯!!

标签: php wordpress advanced-custom-fields


【解决方案1】:

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

返回指定字段的值

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

var_dump( get_field('button_link') ) 

探索输出。此外,根据“检查值是否存在”下的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' ) );

【讨论】:

  • 马克西莫你拯救了一天!感谢您的回答,我刚刚将其添加到我的模板中,并从用户的角度对其进行了测试,并且效果很好!我确实想过像这样嵌套它,但没有尝试!为帮助喝彩。 - 将其标记为已回答 :) 干杯!!
  • 不客气,很高兴我能帮上忙。如果您想避免多个嵌套 AND,您可以编写一个迷你函数,例如:function is_field_set( $field ) { return ( $field ) ? true : false; } 这样您就可以安全地执行if ( is_field_set( get_field( 'one' ) ) &amp;&amp; is_field_set( get_field( 'two' ) ) ) ...
猜你喜欢
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
  • 2015-09-27
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
相关资源
最近更新 更多