我写了这个脚本来列出与帖子相关的邻居:
<div class="neighborhood">What'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。非常感谢您的帮助。
最合适的回答,由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'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>\';
}
更多信息: