2017-05-02 60 views
0

好吧,我想要通过meta_key对与帖子相关的所有评论进行排序。使用WP_Comment_Query获得评论

它目前显示所有评论与喜欢,但不显示没有任何喜欢的评论现在。

下面是该查询:

$args = array(
    'post_id' => intval($_SESSION['thePostId']), 
    'meta_key' => 'cld_like_count', 
    'orderby' => 'meta_value', 
    'order' => 'DESC', 
    'parent' => '0', 
); 

// The Query 
$comments_query = new WP_Comment_Query; 
$comments = $comments_query->query($args); 

我想它显示的所有意见,不只是喜欢的人。
不知道如何去做这件事。

回答

0

你得到的是WordPress的默认行为;如果你是 按特定键排序,那么你必须确保它存在,否则WordPress会忽略它。
解决方案:您必须确保 发布评论时添加了自定义元字段;使用 comment_postupdate_comment_meta

下面是一个代码,将做到上面的任务给你。

add_action('comment_post', 'wh_checkAndAddLike', 10, 2); 

function wh_checkAndAddLike($comment_ID, $comment_approved) 
{ 
    $like_key = 'cld_like_count'; 

    $comment_details = get_comment($comment_ID); 
    $comment_post_id = $comment_details->comment_post_ID; 

    //fetch like comment meta 
    $meta_values = get_comment_meta($comment_ID, $like_key, TRUE); 

    //if like meta key is not present then add a key 
    if (($meta_values == FALSE) && (get_post_type($comment_post_id) == 'post')) //replace post with your post_type 
    { 
     update_comment_meta($comment_ID, $like_key, 0); 
    } 
} 

代码放在functions.php文件的活跃儿童主题(或主题)的。或者也可以在任何插件php文件中使用。
代码已经过测试和工作。

希望这会有所帮助!