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("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac7d3cfc7cbc3c6eacbc8c9ce84c9c5c7">[email protected]</a>", $subject, $message);
}
add_action('publish_post', 'notifyauthor');
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0