您可以使用tax query! 此代码段还利用了wp_list_pluck
, 一个超级方便的函数,用于从对象数组中“提取”属性(在本例中,从术语对象数组中获取术语ID数组):
// Get current posts location term(s)
$locations = get_the_terms( null, \'location_taxonomy\' );
if ( $locations && ! is_wp_error( $locations ) /* Can\'t be too careful */ ) {
$schools = new WP_Query([
\'posts_per_page\' => 5,
\'no_found_rows\' => true,
\'post_type\' => \'school_post_type\',
\'tax_query\' => [
[
\'taxonomy\' => \'location_taxonomy\',
\'terms\' => wp_list_pluck( $locations, \'term_id\' ),
]
]
]);
}
Update: 要与当前代码集成,请执行以下操作:
$current_post_type = get_post_type( $post );
$locations = get_the_terms( $post, \'location_taxonomy\' );
// The query arguments
$args = array(
\'posts_per_page\' => 3,
\'order\' => \'DESC\',
\'orderby\' => \'ID\',
\'post_type\' => $current_post_type,
\'post__not_in\' => array( $post->ID ),
\'no_found_rows\' => true, // Performance boost
);
if ( $locations && ! is_wp_error( $locations ) ) {
$args[\'tax_query\'] = array(
array(
\'taxonomy\' => current( $locations )->taxonomy,
\'terms\' => wp_list_pluck( $locations, \'term_id\' ),
)
);
}
// Create the related query
$rel_query = new WP_Query( $args );