0

有没有办法我从这个 foreach 循环的列表中排除一位老师(“罗伯特”)并将他的条目单独放在顶部?

$teachers = get_terms('teacher');
foreach($teachers as $teacher) {
  $link = get_term_link(intval($teacher->term_id),'teacher');
  $description = term_description(intval($teacher->term_id),'teacher');
  echo "<h3><a href=\"{$link}\">{$teacher->name}</a></h3>";
  echo substr($description,0,200) . "...";
  }

“老师”是一个 Wordpress 分类术语。我正在尝试创建一个所有教师的列表,其中 Robert 位于顶部,因为他是班主任。

4

1 回答 1

2

由于显而易见的原因,这种解决方案是浪费的,例如,您可以将内部细节放入部分中以节省重复回显代码两次(不要重复自己,干)。修改生成查询也会更好,因此校长始终是第一个结果,但请理解您使用的框架可能无法做到这一点。

最好使用抽象的“校长”值进行检查,而不是对名称进行硬编码。

$teachers = get_terms('teacher');
foreach($teachers as $teacher) {
    if($teacher->name == 'Robert') {
      $link = get_term_link(intval($teacher->term_id),'teacher');
      $description = term_description(intval($teacher->term_id),'teacher');
      echo "<h3><a href=\"{$link}\">{$teacher->name}</a></h3>";
      echo substr($description,0,200) . "...";
    }
}

foreach($teachers as $teacher) {
    if($teacher->name != 'Robert') {
      $link = get_term_link(intval($teacher->term_id),'teacher');
      $description = term_description(intval($teacher->term_id),'teacher');
      echo "<h3><a href=\"{$link}\">{$teacher->name}</a></h3>";
      echo substr($description,0,200) . "...";
    }
}
于 2012-11-04T15:16:32.230 回答