您可以添加必要的参数,以仅请求具有相关诊所ID的帖子。
e、 g。
$q = new WP_Query( [
\'post_type\' => \'doctors\',
\'meta_key\' => \'clinic_id\',
\'meta_value\' => get_queried_object_id(),
] );
然而,您在数据结构的设计方式上有一个根本性的错误。可过滤字段应该存储为术语/分类法,而不是post meta。
当你已经知道帖子的ID,但你不知道这里的ID,这就是你要查询的内容时,Post meta的构建速度是非常快的。这将生成此查询extremely expensive and slow. 如果没有一个很好的缓存系统,服务器将在中等甚至轻负载的情况下运行,并且如果您访问数千个帖子(包括所有类型的帖子,而不仅仅是医生),可能会出现更多的根本问题。
相反,使用分类法存储诊所ID,其中术语slug是ID。不要使用post-meta。
Here is code that will automatically create the term when a clinic is created:
add_action( \'save_post\', function ( $post_id, $post ) {
$post_type = get_post_type( $post_id );
// If this isn\'t a \'clinic\' post, skip
if ( \'clinic\' != $post_type ) {
return;
}
wp_insert_term( $post->post_title, \'clinics\', [
\'slug\' => $post_id
]);
} );
This will delete the term when the clinic is deleted:
add_action( \'before_delete_post\', function ( $post_id ) {
$post_type = get_post_type( $post_id );
// If this isn\'t a \'clinic\' post, skip
if ( \'clinic\' != $post_type ) {
return;
}
$term = get_term_by( \'slug\', strval( $post_id ) ,\'clinics\' );
if ( false !== $term ) {
wp_delete_term( $term_id, \'clinics\' );
}
} );
This function will convert a post from post meta to using the taxonomy:
function wpse276842_convert_clinic_meta_to_terms( $post_id ) {
$clinic_ids = get_post_meta( $post_id, \'clinic_id\', false );
if ( empty( $clinic_ids ) ) {
return; // none were found!
}
$slugs = [];
foreach ( $clinic_ids as $id ) {
$slugs[] = strval( $id );
}
wp_set_object_terms( $post_id, $slugs, \'clinics\', true );
}
If you want to retrieve which clinics a post/doctor appears in:
$terms = wp_get_object_terms( $post_id, \'clinics\' );
foreach( $terms as $term ) {
echo \'<p>\'.$term->name.\'</p>\';
echo get_term_link( $term, \'clinics\' );
$clinic = get_post( $term->slug ); // gets the original clinic post
}
一
add_action( \'before_delete_post\', function ( $post_id ) {
$post_type = get_post_type( $post_id );
// If this isn\'t a \'clinic\' post, skip
if ( \'clinic\' != $post_type ) {
return;
}
$term = get_term_by( \'slug\', strval( $post_id ) ,\'clinics\' );
if ( false !== $term ) {
wp_delete_term( $term_id, \'clinics\' );
}
} );