如何修改代码实现仅在自定义文章类型评论时发送作者邮件
解决方法
要实现仅在特定自定义文章类型(CPT)的文章收到评论时发送邮件通知,核心是先判断评论所属文章的类型,非目标类型则终止执行。具体修改如下:
关键修改逻辑
- 通过
get_post_type()获取评论对应文章的类型 - 添加条件判断:仅当文章类型匹配你的自定义类型时,才继续执行邮件发送流程
- 补全函数的完整定义(原代码缺少函数开头部分)
修改后的完整代码
function notify_postauthor_comment($comment_id, $approved) { // 可选:跳过未通过审核的评论,不需要可删除此段 if ($approved !== 1) { return; } $comment = get_comment($comment_id); $post_ID = $comment->comment_post_ID; // 替换为你的自定义文章类型slug,比如'examen' $target_cpt = 'examen'; $post_type = get_post_type($post_ID); // 非目标CPT则直接终止,不发送邮件 if ($post_type !== $target_cpt) { return; } $author_ID = get_post_field('post_author', $post_ID); $user_info = get_userdata($author_ID); $email = $user_info->user_email; $pTitle = get_the_title($post_ID); // 改用get_the_title更可靠 $cAuthor = $comment->comment_author; $cContent = $comment->comment_content; $cUrl = get_comment_link($comment_id); $to = $email; $subject = '¡Tu examen, "'.$pTitle.'" ha sido corregido!'; $headers[] = 'Desde: mi email'; $headers[] = 'Content-Type: text/html; charset=UTF-8'; ob_start(); include("template/email_header.php"); ?> <p>Ya te tienes tu examen corregido <?php echo $pTitle; ?>. Esta es tu nota y comentario:</p> <p><?php echo $pTitle; ?></p> <p><strong>Comentario:</strong><br> <?php echo $cContent; ?></p><br><br> <p>Si necesitas volver a intentarlo vuelve a enviar el audio desde aquí. <strong><a href="">Volver a repetirlo</a></strong><br> <p><strong>Singerfit</strong><br> <?php include("template/email_footer.php"); $message = ob_get_contents(); $message = stripslashes($message); ob_end_clean(); wp_mail($to, $subject, $message, $headers); } add_action('comment_post', 'notify_postauthor_comment', 11, 2);
注意事项
- 务必将
$target_cpt = 'examen';中的examen替换为你实际使用的自定义文章类型slug(即注册CPT时设置的标识名) - 若不需要过滤未审核评论,可删除
if ($approved !== 1)这段判断 - 改用
get_the_title($post_ID)获取文章标题,避免因comment对象数据不全导致标题为空的问题
内容的提问来源于stack exchange,提问作者Laurapnunez
相关产品推荐
相关产品推荐

