You can use a tax query! This snippet also makes use of wp_list_pluck
, a super handy function for “plucking” properties from an array of objects (in this case, getting an array of term IDs from an array of term objects):
// 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: To integrate with your current code:
$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 );