The WP_Comment_Query
class supports ordering by:
'comment_agent',
'comment_approved',
'comment_author',
'comment_author_email',
'comment_author_IP',
'comment_author_url',
'comment_content',
'comment_date',
'comment_date_gmt',
'comment_ID',
'comment_karma',
'comment_parent',
'comment_post_ID',
'comment_type',
'user_id',
'comment__in',
'meta_value',
'meta_value_num',
There's a way to adjust it via filters so we can support ordering by the post title:
$args = [
'status' => 'approve',
'post_status' => 'publish',
'post_type' => 'post',
'orderby' => '_post_title', // <-- Our custom orderby value
'order' => 'DESC'
];
$comment_query = new WP_Comment_Query( $args );
A simple demo plugin to support the _post_title
ordering could be in PHP 7:
/**
* Adjust orderby comments clause
*/
add_filter( 'comments_clauses', function( $clauses, \WP_Comment_Query $cq ) use ( &$wpdb )
{
$qv = $cq->query_vars;
$orderby = $qv['orderby'] ?? '';
$order = $qv['order'] ?? 'ASC';
if(
'_post_title' === $orderby
&& in_array( strtoupper( $order ), [ 'ASC', 'DESC' ], true )
)
$clauses[ 'orderby' ] = " {$wpdb->posts}.post_title {$order},
{$wpdb->comments}.comment_ID {$order} ";
return $clauses;
}, 10, 2 );
and then to make sure the posts table is joined to the comment table, we can set the post type parameter to 'post' if it's missing:
/**
* Make usre we have the posts table joined by making sure the post_type isn't empty.
*/
add_action( 'pre_get_comments', function( \WP_Comment_Query $cq )
{
$qv = &$cq->query_vars;
$orderby = $qv['orderby'] ?? '';
if( '_post_title' === $orderby && empty( $qv['post_type'] ) )
$qv['post_type'] = 'post';
} );
Note that this kind of query:
SELECT wp_comments.comment_ID
FROM wp_comments JOIN wp_posts ON wp_posts.ID = wp_comments.comment_post_ID
WHERE ( comment_approved = '1' )
AND wp_posts.post_status IN ('publish')
AND wp_posts.post_type IN ('post')
ORDER BY wp_posts.post_title DESC, wp_comments.comment_ID DESC
is not efficient as it uses temporary and filesort.
Hope you can adjust it further to your needs.