WordPress自动评论问题:自动生成的评论为何被标记为'post-trashed'?
问题描述
搭建WordPress网站后,在主题functions.php中添加了自定义自动评论功能,期望发布post_type为question的文章时自动插入评论。但实际发布后,数据库中该类文章的自动评论comment_approved属性会自动变为post-trashed,即使代码中已将其设为1。网站未安装任何插件,相关代码如下:
function ic_wp_insert_comment($postId) { $post = get_post($post_ID); $status = $post->post_status; $post_type = $post->post_type; #console_log($post_ID); #console_log($status); #console_log($post_type); if($status == 'publish') { #if($post_type == 'question') #{ if (comments_open( $postId ) ) { $data = array( 'comment_post_ID' => $postId, 'comment_content' => 'hello,my name is chatgpt. now i would like to introduce myself.', 'user_id' => 24, 'comment_author' => 'chatgpt', 'comment_author_email' => 'markmaandmark@outlook.com', 'comment_approved' => 1 ); $comment_id = wp_insert_comment( $data ); if ( ! is_wp_error( $comment_id ) ) { echo 'auto comment error'; return $comment_id; } } #} } return false; } add_action( 'wp_insert_post', 'ic_wp_insert_comment',99,1);
- 网站及文章截图:展示了网站中
question类型文章的发布状态界面 - 评论截图:展示了无问题文章回复评论的界面
问题分析与解决方案
问题原因
- 变量名不一致:函数参数为
$postId,但内部调用get_post($post_ID)时使用了未定义的$post_ID,导致无法正确获取文章对象,后续状态判断失效,可能触发异常导致评论状态被篡改。 - 钩子触发时机不当:
wp_insert_post钩子会在文章创建、更新、草稿转发布等多个场景触发,可能导致评论插入后被后续操作意外修改状态。 - 错误判断逻辑颠倒:代码中
if (!is_wp_error($comment_id))时输出错误提示,逻辑完全相反,无法正确捕获插入失败的情况。 - 未限制目标文章类型:原本针对
question类型的判断被注释,导致所有类型文章都会触发自动评论,不符合需求。
修正后的代码
function ic_wp_insert_comment($postId) { // 获取文章对象,确保变量名与参数一致 $post = get_post($postId); if (!$post) return false; $status = $post->post_status; $post_type = $post->post_type; // 仅在发布question类型文章时执行 if ($status == 'publish' && $post_type == 'question') { if (comments_open($postId)) { $data = array( 'comment_post_ID' => $postId, 'comment_content' => '你好,我是ChatGPT,现在来介绍一下我自己。', 'user_id' => 24, 'comment_author' => 'ChatGPT', 'comment_author_email' => 'markmaandmark@outlook.com', 'comment_approved' => 1 ); $comment_id = wp_insert_comment($data); // 正确判断错误并记录日志 if (is_wp_error($comment_id)) { error_log('自动评论插入失败:' . $comment_id->get_error_message()); return false; } return $comment_id; } } return false; } // 使用针对question类型的save_post钩子,减少不必要触发 add_action('save_post_question', 'ic_wp_insert_comment', 99, 1);
关键修正点
- 统一变量名:将内部
$post_ID改为$postId,确保能正确获取文章信息。 - 精准触发钩子:使用
save_post_question钩子,仅在question类型文章保存时执行,避免其他场景干扰。 - 恢复文章类型判断:取消注释并正确校验
post_type为question,只针对目标文章执行。 - 修正错误判断逻辑:当插入评论失败时记录错误日志,便于排查问题。
- 增加对象校验:先判断
$post是否存在,避免无效操作。
内容的提问来源于stack exchange,提问作者ma mark
相关产品推荐
相关产品推荐

