## wp admin – How to sort comments in the “edit-comments.php” table based on a comment meta field?

Question

### Goal

Sort comments in the “edit-comments.php” table based on a comment meta field after clicking on the title of a custom made column.

### Context

For the sake of brevity let’s assume that when a comment is posted, a meta field called “hearts” is assigned to it so that all comments have that field which is a positive int from 0 to 10. Of the bold steps mentioned below, the first three are given for context and work as intended, the problem is on the 4th step.

1. Creating the column

add_filter( 'manage_edit-comments_columns', 'hearts_add_comments_column' );
function hearts_add_comments_column( $cols ) {$cols['hearts'] = 'Hearts';
return $cols; }  2. Populating the column add_action( 'manage_comments_custom_column', 'hearts_column_content', 10, 2 ); function hearts_column_content($column, $comment_ID ) { switch ($column ) :
case 'hearts' : {
$hearts = get_comment_meta($comment_ID, 'hearts', true );
echo $hearts; break; } endswitch; }  3. Making the column sortable add_filter( 'manage_edit-comments_sortable_columns', 'hearts_make_sortable' ); function hearts_make_sortable($cols ) {
$cols['hearts'] = 'by_hearts'; return$cols;
}


4. Sort based on comment meta

This is where the problems start, something needs to change in the following code which when tested independently, returns a sorted list of comments as intended:

add_action( 'pre_get_comments', 'hearts_orderby' );
function hearts_orderby( $comments_query ) {$orderby = $comments_query->query_vars['orderby']; if( 'by_hearts' ==$orderby ) {
$comments_query->query(array( 'meta_key' => 'hearts', 'orderby' => 'meta_value_num' )); } }  Critical Error when clicking on the column’s title “Hearts” to sort the column. Redirection to an empty page with the following message: Things tried The code below gives no errors, the comments are listed but are not sorted. If i remove the code below entirely, the result is the same. The code is based on the last snippet of this page. add_action( 'pre_get_comments', 'hearts_orderby' ); function hearts_orderby($comments_query ) {
$orderby =$comments_query->query_vars['orderby'];

if( 'by_hearts' == $orderby ) {$comments_query->set('meta_key','hearts');
}
}


### Questions

1. Is it possible to somehow alter the hearts_orderby() function in the 4th step to get the desired outcome?
2. Is it possible to use a different hook in the 4th step?
0
3 weeks 2021-08-30T07:56:33-05:00 0 Answers 0 views 0