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

报告相同问题?

悬赏问题

  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具