我有两种自定义的帖子类型,叫做问答。问题列表包括一个自定义列,其中显示每个问题的答案计数。我需要能够根据答案的数量对列表进行排序。
此查询通过MySQL shell工作,并提供正确的输出:
SELECT a.ID, a.post_title, COUNT(b.ID) AS child_count
FROM wp_posts a
LEFT JOIN wp_posts b
ON a.ID = b.post_parent AND b.post_status = \'publish\' AND b.post_type = \'answer\'
WHERE a.post_type = \'question\' AND a.post_status = \'publish\'
GROUP BY a.ID
ORDER BY child_count DESC
迄今为止我的代码:
add_filter( \'pre_get_posts\', \'column_orderby\' );
function column_orderby( $query ) {
if ( ! is_admin() )
return;
$orderby = $query->get( \'orderby\' );
if ( \'qa-answers\' == $orderby ) {
global $wpdb;
$query->set( \'posts_join\', "LEFT JOIN wp_posts b ON a.ID = b.post_parent AND b.post_status = \'publish\'" );
$query->set( \'posts_groupby\', "{$wpdb->posts}.ID" );
}
}
如何才能
COUNT(b.ID) AS child_count
子句,以便我可以在
$query->set(\'orderby\', \'child_count\');
陈述