【问题标题】:Ternary Operator for Advanced Custom Fields高级自定义字段的三元运算符
【发布时间】:2015-08-03 21:58:38
【问题描述】:

我一直在广泛使用高级自定义字段创建自己的 WP 主题,并且我继续输入代码,例如:

<?php
if(get_field('featured_courses_heading_text', 'option')) {
    echo get_field('featured_courses_heading_text', 'option');
}
?>

此代码是否有更精简的版本可以与三元运算符一起使用?我尝试查看文档,但找不到任何东西

【问题讨论】:

    标签: php wordpress wordpress-theming ternary-operator advanced-custom-fields


    【解决方案1】:

    你可以这样做,它会做同样的事情,因为你没有可供输出的替代值。

    <?php echo get_field('featured_courses_heading_text', 'option'); ?> 
    

    但是如果你正在做一个 if else 那么你可以这样做,如果它没有评估为空(假)null, &lt;empty string&gt;, 0, false

    <?php echo get_field('featured_courses_heading_text', 'option') ?: 'nothing here'; ?>
    

    一样
    <?php if(get_field('featured_courses_heading_text', 'option')) { echo get_field('featured_courses_heading_text', 'option'); } else { echo 'nothing here'; }  ?>
    

    【讨论】:

      【解决方案2】:

      我不确定您为什么需要三元运算符;我认为你的代码很好。

      <?php 
          echo get_field('featured_courses_heading_text', 'option') ?: '';
      ?>
      

      【讨论】:

      • 请注意,这只适用于 PHP 5.3 或更高版本:php.net/manual/en/…
      • @TimoSta,你是对的,但我希望这就是问题作者正在使用的。
      猜你喜欢
      • 2017-12-16
      • 2013-07-14
      • 2013-11-25
      • 2012-08-10
      • 1970-01-01
      • 2017-08-28
      • 2018-08-06
      • 2010-12-19
      • 2023-03-07
      相关资源
      最近更新 更多