将类别列表重写为If/Else语句

时间:2013-09-03 作者:Samantha Slade

我写了这个脚本来列出与帖子相关的邻居:

<div class="neighborhood">What&#39;s Happening in:<?php
foreach((get_the_category()) as $childcat) {
  if (cat_is_ancestor_of(12, $childcat)) {
    echo \'<a href="\'.get_category_link($childcat->cat_ID).\'">\';
    echo $childcat->cat_name . \'</a>\';
}}
?></div>
它工作得很好。但我需要将此重写为if/else语句,以防没有邻居分配给“发生了什么”部分不会出现的帖子。

我的PHP不是超级强大,我不知道如何重新构造代码,使其成为有效的if/else。非常感谢您的帮助。

1 个回复
最合适的回答,由SO网友:gmazzap 整理而成

有关说明,请参见代码中的注释

// all the categories for the post
$categories = get_the_category();

// extracts ids form post categories
$categories_ids = wp_list_pluck( $categories, \'term_id\' );

// all the categories id that are descendant of category 12
$children = get_terms(\'category\', array(\'child_of\'=>12, \'fields\'=>\'ids\') );

// all the categories id for the post that are descendant of category 12
$neighborhood = array_intersect($categories_ids, $children);

// show the div only if we have neighborhood 
if ( ! empty($neighborhood) ) {
  echo \'<div class="neighborhood">What&#39;s Happening in:\';
  foreach ( $categories as $cat ) {
    if ( ! in_array($cat->term_id, $neighborhood) ) continue;
    echo \'<a href="\'. get_category_link($cat->term_id) . \'">\' . $cat->name . \'</a>\';
  }
  echo \'</div>\';
}
更多信息:

结束

相关推荐

Link categories to last post

我正在使用wp\\u list\\u categories()显示我的所有类别。但我希望子类别链接到该类别的最后一个帖子。例如: <ul> <li><a href=\"link-to-category-1\">CATEGORY 1</a> <ul> <li><a href=\"link-to-last-post-of-category-1-1\">CATE