我有一个前端表单,它使用wp\\u insert\\u post()以编程方式将帖子插入到状态为“挂起”的站点中。我还使用insert\\u attachment()将提交的文件附加到帖子。
现在,我正在尝试编写代码,自动将帖子内容(包括附件)通过电子邮件发送给网站管理员。下面是我在函数中用来实现这一点的代码。php文件:
// Notify admin on post insert (pending)
add_action(\'wp_insert_post\', \'send_email_on_pending_post_creation\' );
function send_email_on_pending_post_creation( $post_id){
$post_title = get_the_title( $post_id );
$post_url = get_permalink( $post_id );
$post_content = get_post_field(\'post_content\', $post_id);
$subject = \'New post pending!\';
$message = "A new post is pending on the website:";
$message .= "<br><br>";
$message .= "<strong>Post Title: </strong>";
$message .= "<a href=\'" . $post_url . "\'>" .$post_title. "</a>";
$message .= "<br><br>";
$message .= "<strong>Post Content:</strong><br>";
$message .= $post_content;
$message .= "<br><br>";
//$attachments = get_attached_media( \'image\' );
$attachments = get_the_post_thumbnail( $post_id, \'full\' );
$msg_headers = array(\'Content-Type: text/html; charset=UTF-8\', \'From: "Website" < [email protected] >\');
//send email to admin
wp_mail( \'[email protected]\', $subject, $message, $msg_headers, $attachments );
}
现在的问题是,虽然发送的电子邮件带有帖子标题和内容,但附件没有发送。此外,一旦发送电子邮件,进行var\\u转储($附件)最终会变成空的。
请帮我找出我做错了什么,需要做什么。
非常感谢。
编辑:终于找到了解决方案。如果你遇到这个问题,请检查我下面的答案。
最合适的回答,由SO网友:Avinash Kumar 整理而成
在几个地方问了这个问题但没有找到解决方案后,我今天早上自己找到了解决方案。
而不是挂接函数send_email_on_pending_post_creation
对于“wp\\u insert\\u post”操作,您需要将其挂接到“add\\u attachment”操作,该操作在插入帖子后以及将附件添加到帖子时发生。您还需要更新send_email_on_pending_post_creation
函数获取post_parent
(附件附加到的父帖子ID),以便post_title
, post_url
和post_content
变量返回正确的值。
以下是更新的send_email_on_pending_post_creation
向管理员发送带有附件链接的电子邮件的功能。
add_action(\'add_attachment\', \'send_email_on_pending_post_creation\' );
function send_email_on_pending_post_creation( $post_id ){
$attachment = get_post($post_id);
$attachment_title = get_the_title($post_id);
$parent_id = $attachment->post_parent;
$post_title = get_the_title( $parent_id );
$post_url = get_permalink( $parent_id );
$post_content = get_post_field(\'post_content\', $parent_id);
$subject = \'New post pending!\';
$attachments = wp_get_attachment_url($post_id);
$message = "A new post is pending on the website:";
$message .= "<br><br>";
$message .= "<strong>Post Title: </strong>";
$message .= "<a href=\'" . $post_url . "\'>" .$post_title. "</a>";
$message .= "<br><br>";
$message .= "<strong>Post Content:</strong><br>";
$message .= $post_content;
$message .= "<br><br>";
$message .= "<strong>Attachment:</strong><br><br>";
$message .= "<a href=\'". $attachments . "\' title=\'". $attachment_title . "\'>" . $attachment_title . "</a>";
$message .= "<br><br>";
$msg_headers = array(\'Content-Type: text/html; charset=UTF-8\', \'From: "Website" < [email protected] >\');
//send email to admin
wp_mail( \'[email protected]\', $subject, $message, $msg_headers, $attachments );
}
希望它能帮助别人!