如评论中所述,而不是使用ID
获取每个\'calp_event\'
-单独键入post,可以将ID数组传递给post__in
为了一次抓取它们,从而将代码中的数据库事务数减少到2个。
通过从第三方表查询的结果创建一个将post ID映射到事件开始日期的数组,可以轻松获得要传递到的值post__in
通过使用array_keys()
获取just-post-id的数组。然后在后面的循环中,您可以使用相同的post ID来查找开始日期映射。
由于您以类似于WordPress的“循环”的方式循环查询结果并使用模板标记,因此您还可以考虑使用新的WP_Query
对象而不是get_posts()
允许您使用更传统的“循环”逻辑来显示结果。
global $wpdb;
$today = date(\'Y-m-d\');
$events = $wpdb->get_results( "SELECT * FROM " . $wpdb->prefix . "calp_events WHERE start >= \'$today\' ORDER BY start ASC LIMIT 5" );
// Create an array using event post IDs as keys and start dates as values
$eventDates = array();
foreach( $events as $event ) {
$eventDates[ $event->post_id ] = $event->start;
}
// Query for the \'calp_event\' posts indicated by the earlier query.
// Since the keys of $eventDates are the post IDs returned by the previous query,
// array_keys( $eventDates ) will return an array consisting of those IDs
$eventQuery = new WP_Query( array(
\'post_type\' => \'calp_event\',
\'post__in\' => array_keys( $eventDates )
) );
// Use conventional Loop logic to display your results
if( $eventQuery->have_posts() ) {
while( $eventQuery->have_posts() ) {
$eventQuery->the_post();
// Accessing the $eventDates array with the current post ID as a key will produce
// the event start date which that ID is mapped to.
echo $eventDates[ get_the_ID() ] . \' \' . the_title() . \'<br>\';
}
// Reset global post data so we don\'t muck up the main query
wp_reset_postdata();
}
else {
echo \'No upcoming events!\';
}
您可以通过使用更高级的SQL一次性获取所有必要的帖子和事件开始日期,将其简化为单个查询。