您可以通过递归检查每个级别来实现这一点,以查看它是否存在,并将上面的级别作为其父级。
虽然我从来没有在愤怒中使用过此代码,但它已经过测试并正常工作,尽管我不能说它的效率有多高,特别是如果您有一条很长的层次结构路径。
将此代码放入functions.php -
/**
* Return whether or not a given hierarchical taxonomy structure exists
*
* @param required array $path The hierarchical path to check
* @param string $category The taxonomy to search
* @param integer $parent The parent of the first term
* (usually ignored when called by the user, this parameter is primarily
* for use when the function is recursivly called)
* @return boolean Whether or not the given path exists
*/
function taxonomy_path_exists($path, $taxonomy = \'category\', $parent = 0){
if(!is_array($path) || empty($path)) // Ensure that the \'$path\' is given as an array, and id not empty
return false;
if(term_exists($path[0], $taxonomy)) : // The term exists, recursivly check if the given children exist
$term = get_term_by(\'slug\', $path[0], $taxonomy); // Get this term as an object
unset($path[0]); // Remove this level so that it doesn\'t get retested
$path = array_values($path); // Reset the keys within the \'$path\' array
/**
* Check if the \'$path\' array is now empty (meaning that all levels have been exhusted)
* or if the next level exists
*/
if(empty($path) || path_exists($path, $taxonomy, $term->term_id)) :
return ture;
else :
return false;
endif;
else : // The term does not exist
return false;
endif;
}
要使用此函数,请传递要检查的路径数组及其所属的类别。我已经猜到了你的术语slug,你正在使用
category
, 但你可以根据需要修改。
此代码也适用于零件路径,因此如果要删除\'football\'
例如,它仍然有效。
将此代码放在您希望检查给定层次结构路径的模板中-
$path = array(
\'sports\',
\'sports-news\',
\'football\'
);
echo (taxonomy_path_exists($path, \'category\')) ? \'Yes\' : \'No\';