doutuobao4004 2017-05-02 02:53
浏览 40

使用WP_Comment_Query获取评论

Ok so I'm trying to sort all comments associated with a post by the meta_key.

It currently displays all the comments with likes, but doesn't show the comments without any likes now.

Here is the 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);

I would like it to display all comments, not just the ones with likes.
Not sure how to go about this.

  • 写回答

1条回答 默认 最新

  • dqf35839 2017-05-02 08:06
    关注

    What you are getting is the WordPress default behaviour; If you are ordering by a specific key then you have to make sure it exists, otherwise WordPress will ignore that.
    Solution: You have to make sure when a comment is posted with that add the custom meta field with it; Using comment_post and update_comment_meta

    Here is a code which will do the above task for you.

    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);
        }
    }
    

    Code goes in functions.php file of your active child theme (or theme). Or also in any plugin php files.
    Code is tested and works.

    Hope this helps!

    评论

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP