如何在插入评论前检查`COMMENT_META`是否存在?

时间:2022-01-05 作者:Rohit kc

我通过插入评论wp_insert_comment 在这样做的同时,我只添加电子邮件回复。现在,我想在插入之前检查注释是否已经存在,如果确实存在,则不执行wp_insert_comment.这是我的代码:

 // Here, we insert the replies as comment to their parent email. 
            if ((!empty($mail[\'header\']->references )) && (preg_replace(\'~[<]~\',\'\',strstr($mail[\'header\']->references, \'@\',true))) == (preg_replace(\'~[<]~\',\'\',strstr($mail[\'header\']->references, \'@\',true))))     
                {
                  //echo htmlentities($mail[\'header\']->message_id);

                $posts = get_posts( array(
                    \'post_type\'  => \'post-type\',
                    \'meta_key\'   => \'ticket_id\',
                    \'meta_value\' => preg_replace(\'~[<]~\',\'\',strstr($mail[\'header\']->references, \'@\',true)),
                ) );
                    
            if ( ! empty( $posts )   ) {
                $comment_array = array(
                    \'comment_content\' => $mail[\'body\'],
                    \'comment_post_ID\' => $posts[0]->ID,
                    \'comment_author\'  => ucwords(strstr($mail[\'header\']->fromaddress, \'<\',true)),
                    \'comment_author_email\' => preg_replace(\'~[<>]~\', \'\', strstr($mail[\'header\']->fromaddress, \'<\')),
                    \'comment_type\'  => \'email_replies\',
                    \'comment_date\'  => $mail[\'header\']->Date,
                    \'comment_meta\'  => preg_replace(\'~[<]~\',\'\',strstr($mail[\'header\']->message_id, \'@\',true)),
                );
                   wp_insert_comment($comment_array);
            }
            }
我还是一个初学者,所以任何帮助都将不胜感激。

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

首先,您需要修复comment_meta 价值应该是array 元键和值对,而不仅仅是元值。

所以给元一个键(或名称),例如。message_id, 然后这样做:

\'comment_meta\' => array(
    \'message_id\' => preg_replace(\'~[<]~\',\'\',strstr($mail[\'header\']->message_id, \'@\',true)),
),
现在,要检查特定meta是否已经存在注释,可以使用get_comments() 还有元查询,就像您使用get_posts().

例如:

$comment_exists = (bool) get_comments( array(
    \'type\'       => \'email_replies\',
    \'meta_key\'   => \'message_id\',
    \'meta_value\' => preg_replace(\'~[<]~\',\'\',strstr($mail[\'header\']->message_id, \'@\',true)),
    \'count\'      => true, // this means we\'re retrieving the number of comments only
) );

if ( ! $comment_exists ) {
    $posts = get_posts( ... );

    if ( ! empty( $posts ) ) {
        // insert the comment
    }
}
顺便说一句,您应该分配上述preg_replace()\'将s值转换为变量,然后将其与comment_metameta_value 在上面