dongyongmin5711 2017-06-05 17:46 采纳率: 100%
浏览 49
已采纳

if语句使用php并在wordpress中提升自定义字段 - 隐藏空字段

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 :)

  • 写回答

1条回答 默认 最新

  • dongshao5573 2017-06-05 18:10
    关注

    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' ) );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog