正如TimMalone所说,WP\\U查询不会在其结果集中返回同一帖子的多个副本。我认为你有一个设计问题,我建议你使用父/子帖子而不是帖子元来完成你想要的。
以下是实现这一点的一种方法。首先,注册两种帖子类型:
// The parent event type
// There will be one of these for Radio Show and TV Show
register_post_type( \'event\', $args );
// A non-public event type for each "occurrence" of an event
// There will be two of these for each Radio Show and TV Show
register_post_type( \'event_occurrence\', array(
// add all of your usual $args and then set public to false
\'public\' => false,
) );
然后,在保存
event
post,不要将开始/结束时间保存为该post对象上的post meta。而是使用这些日期创建
event_occurrence
每次事件的帖子,其中保存了开始和结束时间。
$occurrence_id = wp_insert_post( array(
// add all of your occurrence details and then set the parent
// to the `event` post that\'s being saved
\'post_parent\' => <event_post_id>,
// Set the post date to the start time for efficient ordering
\'post_date\' => $start_time,
) );
// Save the end time as post meta
// Save it as a Unix timestamp so that we can compare it in the query
update_post_meta( $occurrence_id, \'end_time\', strtotime( $end_time ) );
现在,数据库中应该有以下帖子:
Radio Show
Radio Show Instance 1
Radio Show Instance 2
TV Show
TV Show Instance 1
TV Show Instance 2
然后,可以按如下方式查询事件:
$args = array(
// Only fetch occurrences
\'post_type\' => \'event_occurrence\',
// Retrieve only future occurrences
\'date_query\' => array(
array(
\'after\' => \'now\',
)
),
// use a reasonably high posts_per_page instead of -1
// otherwise you could accidentally cripple a site
// with an expensive query
\'posts_per_page\' => 500,
\'post_status\' => \'publish\',
\'meta_query\' => array(
array(
\'key\' => \'end_time\',
\'value\' => time(),
\'compare\' => \'>=\'
),
),
// They\'ll be ordered by start date.
// ASC starts with earliest first
\'order\' => \'ASC\',
);
我们的循环现在将包含四个帖子:
Radio Show Instance 1
Radio Show Instance 2
TV Show Instance 1
TV Show Instance 2
因此,当您在事件中循环时,可以访问每个事件的父帖子,以获取总体事件数据。您可以通过一个简单的函数来实现这一点:
$parent_event_id = wp_get_post_parent_id( get_the_ID() );
然而,这将导致对数据库的大量额外查询,从而影响性能。相反,我建议您对主
event
发布,然后从这些结果中提取它们,因此您只需对数据库进行一个额外的查询:
$args = array(
\'post_type\' => \'event\',
\'date_query\' => array(
array(
\'after\' => \'now\',
)
),
\'posts_per_page\' => 500,
\'post_status\' => \'publish\',
\'meta_query\' => array(
array(
\'key\' => \'end_time\',
\'value\' => time(),
\'compare\' => \'>=\'
),
),
\'order\' => \'ASC\',
);
$events = new WP_Query( $args );
因此,您的$引用循环如下所示:
$occurrences = new WP_Query( $occurrences_args );
while( $occurrences->have_posts() ) {
$occurrences->the_post();
// Get the parent event data
$parent_event_id = wp_get_post_parent_id( get_the_ID() );
$parent_event = null;
foreach ( $events->posts as $post ) {
if ( $post->ID == $parent_event_id ) {
$parent_event = $post;
break;
}
}
// Now you can use the loop to access the
// occurrence data and use $parent_event to
// access the overall event data
}