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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助