I would like to send a notification email (Asana) whenever something is published (posts, pages, custom post types) [duplicate]
質問
The code below works perfectly
When I create a new post, an email is sent out to the email included in the function.
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("myemail@abcd.com", $subject, $message);
}
add_action('publish_post', 'notifyauthor');
解決
The hook that you're currently using is publish_<post type>
which means the <post type>
part is dynamic and the value is a post type name/slug.
So for other post types like page
and (a custom post type named) my_cpt
, you would just need to change the "post" (or the <post type>
part) in the hook name to page
, my_cpt
or whatever is the post type name/slug like so:
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
Or if you want your action (notifyauthor()
) to be called when any posts (regular Posts and Pages, and custom post types) is published, then you would want to use the transition_post_status()
hook instead of the publish_<post type>
hook.
Here's an example based on 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: If you use the above code/hook, then you should remove the add_action('publish_post', 'notifyauthor');
from your current code.