这是开发人员的高级示例。它支持自定义帖子类型和自定义分类法,包括多个分类法的匹配。
// $post pointing to a WP_Post instance of the current post.
$query = new WP_Query(
[
\'post_type\' => $relatedPostType,
\'posts_per_page\' => 6,
\'tax_query\' => buildTaxonomyForRelatedPosts($post),
\'post__not_in\' => [$post->ID],
]
);
// The array of related posts
$relatedPosts = $query->get_posts();
function buildTaxonomyForRelatedPosts(WP_Post $post) {
switch ($post->post_type) {
case \'post\':
$taxonomies = [\'category\', \'post_tag\'];
break;
case \'news\':
$taxonomies = [\'newscategory\', \'newstags\'];
break;
default:
return [];
}
$taxQuery = [
\'relation\' => \'OR\',
];
foreach ($taxonomies as $taxonomy) {
$taxQuery[] = [
\'taxonomy\' => $taxonomy,
\'field\' => \'slug\',
\'terms\' => array_filter(wp_get_object_terms($post->ID, $taxonomy, [\'fields\' => \'slugs\']), function($termSlug) {
return strtolower($termSlug) !== \'uncategorized\';
}),
];
}
return $taxQuery;
}
功能
buildTaxonomyForRelatedPosts
基本上使用以下结构构建阵列:
\'tax_query\' => [
\'relation\' => \'OR\',
[
\'taxonomy\' => \'movie_genre\',
\'field\' => \'slug\',
\'terms\' => [\'action\', \'comedy\', \'drama\'],
],
[
\'taxonomy\' => \'actor\',
\'field\' => \'slug\',
\'terms\' => [\'foo\', \'bar\', \'baz\'],
],
];
https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters