编辑
NOTE 如果您只需要父级和一级子级术语,@Roberthue的答案应该很有用。如果您需要所有级别的子术语,那么我的解决方案应该可以使用
我已经更新了代码以提高效率。
运行get_ancestors()
只有当我们找不到父项或其直接子项时
当我们从中找到父项时,立即停止foreach循环的执行get_ancestor
作用
将我的支票拆分为小块,当我的支票返回true时,立即停止执行默认情况下,没有选项为特定类别的帖子设置特定模板。尽管如此,这并不意味着它不能做到。要实现这一点,您需要使用single_template
filter 将自定义单模板页面设置为具有特定类别集的帖子。
您可以尝试以下操作:(CAVEAT: 该代码未经测试,至少需要PHP 5.3)
add_filter( \'single_template\', function ( $template )
{
// Get the current queried post id
$current_post = get_queried_object_id();
// Get the post terms. Change category to the correct taxonomy name if your post terms is from a custom taxonomy
$terms = wp_get_post_terms( $current_post, \'category\' );
// Check if we have terms and we don\'t have an error. If we do, return default single template
if ( !$terms || is_wp_error( $terms ) )
return $template;
// Check if our custom template exists before going through all the trouble to find out terms
$new_template = locate_template( \'single-custom.php\' );
if ( !$new_template )
return $template;
// Get al the term ids in an array and check if we can find our parent term
$term_ids = wp_list_pluck( $terms, \'term_id\' );
if ( in_array( 10, $term_ids ) )
return $template = $new_template;
// Get all the parent ids in an array and look for our parent term if we could not find it using term ids
$parent_ids = wp_list_pluck( $terms, \'parent\' );
if ( in_array( 10, $parent_ids ) )
return $template = $new_template;
// If we cannot find the parent or direct children, lets look for lower level children
$bool = false;
foreach ( $term_ids as $term ) {
// Use get_ancestors and check if we can find our parent term id
if ( in_array( 10, get_ancestors( $term, \'category\' ) ) ) {
$bool = true;
// If we found our parent, stop execution of our foreach loop
break;
}
}
// If $bool is true, return our custom single template
if ( $bool )
return $template = $new_template;
// If all our conditions failed, return the default single template
return $template;
});
编辑2上述代码现已测试并运行。修复了几个小错误:-)