我想在发布内容(帖子、页面、自定义帖子类型)时发送通知电子邮件(Asana)

时间:2021-04-09 作者:Neha Patel

下面的代码工作正常

创建新帖子时,会向功能中包含的电子邮件发送一封电子邮件。

I would like to know how I can send an email when anything is published on the website, like custom post types, pages and regular posts

function notifyauthor($post_id) {
 
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post Published: ".$post->post_title."";
 
$message = "
      Hi ".$author->display_name.",
       
      Your post, \\"".$post->post_title."\\" has just been published.
       
      View post: ".get_permalink( $post_id )."
       
      Thanks"
      ;
       
   wp_mail("[email protected]", $subject, $message);
}
add_action(\'publish_post\', \'notifyauthor\');

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

您当前使用的挂钩是publish_<post type> 这意味着<post type> part是动态的,值是post类型名称/slug。

所以对于其他类型的帖子,比如page 和(名为的自定义帖子类型)my_cpt, 您只需更改;“发布”;(或<post type> 部件)在挂钩名称中page, my_cpt 或者不管帖子类型名称/slug是什么:

add_action( \'publish_post\', \'notifyauthor\' );   // for the default \'post\' post type
add_action( \'publish_page\', \'notifyauthor\' );   // for the default \'page\' post type
add_action( \'publish_my_cpt\', \'notifyauthor\' ); // for a CPT with the name/slug my_cpt
或者如果你想采取行动(notifyauthor()) 要在发布任何帖子(常规帖子和页面,以及自定义帖子类型)时调用,则需要使用transition_post_status() hook 而不是publish_<post type>

下面是一个基于this on the WordPress Developer Resources site:

function wpdocs_run_on_publish_only( $new_status, $old_status, $post ) {
    // Yes, I said "any posts", but you might better off specify a list of post
    // types instead. Or you could do the check in your notifyauthor() function
    // instead.
    $post_types = array( \'post\', \'page\', \'my_cpt\', \'foo_bar\', \'etc\' );

    if ( ( \'publish\' === $new_status && \'publish\' !== $old_status ) &&
        in_array( $post->post_type, $post_types )
    ) {
        notifyauthor( $post->ID );
    }
}
add_action( \'transition_post_status\', \'wpdocs_run_on_publish_only\', 10, 3 );
PS:如果您使用上述代码/挂钩,那么您应该删除add_action(\'publish_post\', \'notifyauthor\'); 从当前代码。

相关推荐

如何为所有特色图像设置Status=‘Publish’?

背景:我遇到了这个WP问题:https://core.trac.wordpress.org/ticket/41445简而言之:当您通过REST API向帖子发出请求时,如果特色图片最初上载到其他帖子,而此帖子无法通过REST API访问(例如,原始帖子被丢弃,是草稿等),您将获得403 error.这是WordPress API中的一个bug,尚未修复。显然,之所以会发生这种情况,是因为所有附件都从其父帖子继承了状态(在数据库中,post_status=\'inherit\')可能的解决方法如下this