How can I organize comments by like count in WordPress?

Viewed 36

I am using the "Comments Like Dislike" Plugin in WordPress so my users can like other user's comments. This works fine but I am trying to create an addon plugin that will organize the comments by like count. I have been able to reorganize the comments in this way but the issue I am running in to is that users are no longer able to reply to comments because of this change. The like count is stored in wp_commentmeta like below.

comment_id meta_key meta_value
1 cld_like_count 3

My function selects and orders this table by meta value then retrieves the comment ID of each comment. It then uses this array of IDs to organize my comments.

<?php
function like_filter_comments( $comments ) {
    return like_organize_comments( $comments );
    //return $commentsbylike;
}
add_filter ('comments_array', 'like_filter_comments');


//organize comments so that most liked comments appear first
function like_organize_comments($unorganizedComments){
    global $wpdb;
    //$allComments = get_comments();
    
$user_id = 1;

$wpdb_prefix = $wpdb->prefix;
$wpdb_comment = $wpdb_prefix . 'comments';
$wpdb_commentmeta = $wpdb_prefix.'commentmeta';
$meta_commentlike = $wpdb->get_results("SELECT comment_id, meta_key, meta_value FROM $wpdb_commentmeta WHERE meta_key = 'cld_like_count' ORDER BY meta_value DESC;");

$i=0;
foreach($meta_commentlike as $key => $value){
    //print_r( $key);
    $metav =  $value->meta_value;
    $comment = $value->comment_id;

$arr[$i++] =  $comment; //comment_id listed in order by likes

}
    
$commentlike = $wpdb->get_results("
SELECT *
FROM $wpdb_comment
WHERE comment_parent
IN (0)

;");

var_dump($commentlike);
    
return $arr;
    
}

The function above does successfully organize the comments by like count but it removes the ability to reply to comments. I made an attempt to only select comments with no parent but I am having difficulties because comment_parent is in the wp_comment table and the like count meta value is in the wp_commentmeta table. I've looked into joining the tables together but haven't found any similar columns to merge.

0 Answers
Related