我试图完成的事情似乎一点也不复杂。
SQL代码:
SELECT *
FROM wp_posts
WHERE post_type = "event"
AND post_status IN ("publish", "future")
AND post_date > "2015-02-26"
AND post_parent != 0
GROUP BY post_parent
ORDER BY post_date ASC;
我有两种方法可以做到这一点。出于性能原因,我使用第二个选项。
选项1:第一个选项运行两个查询。第一个查询是获取“未来子”事件的ID,第二个查询是仅包括具有所提供ID的子记录。
add_action(\'pre_get_posts\', \'modify_event_pre_get_posts\');
function modify_event_pre_get_posts($query) {
global $wpdb;
if(!is_admin() && $query->is_main_query()) {
if(is_post_type_archive(\'event\')) {
$my_query = $wpdb->prepare(\'SELECT * FROM %1$s WHERE post_type = "event" AND post_status IN ("publish", "future") AND post_date > \'.date(\'Y-m-d\').\' AND post_parent != 0 GROUP BY post_parent ORDER BY post_date ASC;\', $wpdb->posts);
$ids = $wpdb->get_col($my_query);
$query->set(\'post__in\', $ids);
$query->set(\'order\', \'ASC\');
$query->set(\'orderby\', \'post_date\');
$query->set(\'posts_per_page\', -1);
$query->set(\'post_status\', array(\'publish\', \'future\'));
}
}
}
选项2:第二个选项仅运行一个查询。它更改默认的WP数据库查询,以从数据库中获取所需的结果。请注意,我在这里使用了两个挂钩,即pre\\u get\\u posts和posts\\u groupby。
add_action(\'pre_get_posts\', \'modify_event_pre_get_posts\');
add_filter(\'posts_groupby\', \'modify_event_posts_groupby\');
function modify_event_posts_groupby($group_by) {
global $wpdb;
if(!is_admin() && is_main_query()) {
if(is_post_type_archive(\'event\')) {
$group_by = "{$wpdb->posts}.post_parent";
}
}
return $group_by;
}
function modify_event_pre_get_posts($query) {
global $wpdb;
if(!is_admin() && $query->is_main_query()) {
if(is_post_type_archive(\'event\')) {
$query->set(\'post_status\', array(\'publish\', \'future\'));
$query->set(\'date_query\', array(\'after\' => date(\'Y-m-d\')));
$query->set(\'order\', \'ASC\');
$query->set(\'orderby\', \'post_date\');
$query->set(\'post_parent__not_in\', array(0));
}
}
}