parent
这里是你的答案。每个术语在其parent
所有物该值是一个整数值,表示其父项的项id。所有顶级术语的值均为0
这仅仅意味着这是一个顶级术语
首先,我们需要使用父项和get_the_category
. 我们将跳过0
价值观一旦有了ID数组,我们将获得所有唯一的值,并将ID数组传递给tax_query
为了保存多个查询
(以下代码未经测试,需要PHP 5.4+)
function get_related_category_posts()
{
// Check if we are on a single page, if not, return false
if ( !is_single() )
return false;
// Get the current post id
$post_id = get_queried_object_id();
// Get the post categories
$categories = get_the_category( $post_id );
// Lets build our array
// If we don\'t have categories, bail
if ( !$categories )
return false;
foreach ( $categories as $category ) {
if ( $category->parent == 0 ) {
$term_ids[] = $category->term_id;
} else {
$term_ids[] = $category->parent;
$term_ids[] = $category->term_id;
}
}
// Remove duplicate values from the array
$unique_array = array_unique( $term_ids );
// Lets build our query
$args = [
\'post__not_in\' => [$post_id],
\'posts_per_page\' => 3, // Note: showposts is depreciated in favor of posts_per_page
\'ignore_sticky_posts\' => 1, // Note: caller_get_posts is depreciated
\'orderby\' => \'title\',
\'no_found_rows\' => true, // Skip pagination, makes the query faster
\'tax_query\' => [
[
\'taxonomy\' => \'category\',
\'terms\' => $unique_array,
\'include_children\' => false,
],
],
];
$q = new WP_Query( $args );
return $q;
}
然后,您可以在单个贴子页面中使用以下代码
$q = get_related_category_posts();
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// Your loop
}
wp_reset_postdata();
}