dtfbj24048 2013-11-06 17:33
浏览 24
已采纳

PHP中的多个ID在WordPress中调用

** I apologize for being unclear - I meant I want "Summit Sponsors" to display once regardless of how many IDs are used. Just for it to be hidden if no IDs are used. Thanks **

I was wondering if anyone knew a clean way to use multiple custom fields in an IF statement.

At the moment I have it spaced out, so each custom field "SponsorHeading#" has it's own if/else statement:

<?php
if(get_post_meta($post_id, 'SponsorHeading1', true)) {
   echo '<h2>Summit Sponsors </h2>';
}
else {
   echo '';
}
if(get_post_meta($post_id, 'SponsorHeading2', true)) {
    echo '<h2>Summit Sponsors </h2>';
}
else {
    echo '';
} 
?>

and so on for 3 more custom fields. I'd like to have something cleaner like:

<?php
if(get_post_meta($post_id, 'SponsorHeading1', true)) || if(get_post_meta($post_id, 'SponsorHeading2', true)) || if(get_post_meta($post_id, 'SponsorHeading3', true)) {
  echo '<h2>Summit Sponsors </h2>';
}
 else {
        echo '';
}
?>

or something along those lines to clean it up but nothing I've tried has worked.

Any suggestions?

  • 写回答

1条回答 默认 最新

  • doufu6196 2013-11-06 17:40
    关注

    Not 100% sure on if there is a more efficient way to manage this within WordPress’s logic itself, but the simplest solution I can conceive of using the example you give is to put all of the ids into an array & have logic to loop through them like so:

    <?php
    
    $fields = array('SponsorHeading1', 'SponsorHeading2', 'SponsorHeading3');
    
    foreach($fields as $field_value) {
      if(get_post_meta($post_id, $field_value, true)) {
        echo '<h2>Summit Sponsors </h2>';
      }
      else {
        echo '';
      }
    }
    
    ?>
    

    EDIT: Addressing the user edits to the question. So how about this? We loop through the fields, and the value of $has_value changes to TRUE if at least one of the fields is returned by get_post_meta(). And if $has_value is TRUE then act on it:

    <?php
    
    $fields = array('SponsorHeading1', 'SponsorHeading2', 'SponsorHeading3');
    $has_value = FALSE;
    foreach($fields as $field_value) {
      if(get_post_meta($post_id, $field_value, true)) {
        $has_value = TRUE;
      }
    }
    
    if ($has_value) {
      echo '<h2>Summit Sponsors </h2>';
    }
    else {
      echo '';
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建