2017-05-02 59 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文件中使用。
代碼已經過測試和工作。

希望這會有所幫助!