I have a website that, based on a user's comments, filters comments by "most liked first, most disliked first" etc...
I have a custom table for comments scoring system and system working with +1 and -1's.
A few days ago I wanted to filter comments by most liked and most disliked as I said and wrote this code:
In my functions.php
function bestanswers($a){
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_comments LEFT JOIN wp_custom_scoring ON wp_custom_scoring.entryID = wp_comments.comment_ID WHERE class="point" and comment_post_ID='.intval($a).' AND type="plus" GROUP BY entryID ORDER BY COUNT(entryID) DESC');
if(empty($results)){
echo 'Its Empty!';
return false;
}else{
return $results;
}
}
And in my functions.php again:
function score($a,$b){
if($b == "minus"){
global $wpdb;
$results = $wpdb->get_results( 'SELECT count(id) as total,type,class,entryID FROM wp_custom_scoring WHERE type="minus" and class="point" and entryID='.intval($a));
if($results[0]->total!= 0){
return "-".$results[0]->total;
}else{
return 0;
}
}elseif($b == "plus"){
global $wpdb;
$results = $wpdb->get_results( 'SELECT count(id) as total,type,class,entryID FROM wp_custom_scoring WHERE type="plus" and class="point" and entryID ='.intval($a));
if($results[0]->total != 0){
return "+".$results[0]->total;
}else{
return 0;
}
}else{
global $wpdb;
$results = $wpdb->get_results( 'SELECT count(id) as total,class,entryID FROM wp_custom_scoring WHERE class="fav" and entryID='.intval($a));
return $results[0]->total;
}
}
And in comments.php:
if(isset($_GET['filter']) and sanitize_text_field(esc_attr($_GET['filter'])) == 'bestanswers'){
foreach (bestanswers($postID) as $bests) {
if ( score($bests->comment_ID,"plus") + score($bests->comment_ID,"minus") > 0 ){
echo $bests->comment_ID;
comment_text($bests->comment_ID);
///...etc with my custom theme template
}
It's working and I'm able to get everything as I wanted but it's looking ugly to me. Is there are any better way to do this? Or any improvement on my code?
Filtering web comments by votes. Please see the code review guidelines at codereview.stackexchange.com/help/how-to-ask. \$\endgroup\$