问题出在逻辑上。一篇文章可能有几个术语,但并非所有术语都是子术语。例如,考虑parent > child 术语关系:
a > b > c
d > e
f
让我们假设我们的帖子有条款
c,
e 和
f 附属于他们。
现在通过以下循环c,e 和f 反过来但是$parentcat (和$parentcat_nam) 每次都会超出值:
foreach((get_the_category()) as $childcat) {
$parentcat = $childcat->category_parent;
$parentcat_name = get_cat_name($parentcat);
}
所以
$parentcat 将设置为中最后一个术语的父项的ID
get_the_category(). 如果是的话
c 它的ID是
b. 但如果是的话
f, 它将为0,因此“无法找到父类别”。
现在还不清楚在与父母多个学期的情况下你想做什么。如果你只想要一个父母,那么你可以break 超出foreach 环
foreach((get_the_category()) as $childcat) {
if( !empty($childcat->category_parent) ){
$parentcat = $childcat->category_parent;
$parentcat_name = get_cat_name($parentcat);
break;
}
}
//$parentcat is set the ID of the parent of one of the terms, 0 if all terms have no parent.
如果要存储帖子术语的所有父项的ID,可以将它们存储在一个数组中
$parentcat_arr=array();
foreach((get_the_category()) as $childcat) {
if( !empty($childcat->category_parent) ){
$parentcat_arr[] = $childcat->category_parent;
break;
}
}
//$parentcat_arr stores array of IDs corresponding to the parents of the post\'s terms
//If its empty, then the post has no terms with parents.