Send notification to the admin when new custom post is submitted

I have a cpt called "auto" and i make a frontend form to create new post with "pending" status. After the post submission i would receive an email with a notification of the new post.

function newpost_notify() {

  $mailadmin = '[email protected]';
  $subject = 'Subject';
  $headers  = 'MIME-Version: 1.0' . "\r\n";
  $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";    
  $headers .= 'From: xxx [email protected]' . "\r\n";
  $message = 'There\'s a new post.';

  wp_mail( $mailadmin, $subject, $message, $headers );
}

add_action( 'publish_post', 'newpost_notify', 10, 2 );

This is my code..but i didn't receive any email.

I would know if there's a difference between a "new post" and a "publish post", because i read something about the post status transition.

Thank you

Topic wp-mail notifications customization custom-post-types Wordpress

Category Web


The accepted answer does not work for me in 2021. I suspect that the action hook name(s) have changed.

Here's the updated solution that's working for me:

function newpost_notify( $auto ) {

  $mailadmin = '[email protected]';
  $subject = 'Subject';
  $headers  = 'MIME-Version: 1.0' . "\r\n";
  $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";    
  $headers .= 'From: xxx <[email protected]>' . "\r\n";
  $message = 'There\'s a new post.';

  wp_mail( $mailadmin, $subject, $message, $headers );
}

add_action( 'pending_auto', 'newpost_notify', 10, 2 );

Note that the action name is dynamic, so you will need to adjust the first argument of add_action to match your custom post_type. The format is {status}_{postType}.

Also note that the argument passed to the callback function is the post ID of the new post (not an instance of WP_Post).


EDIT - SOLUTION

I got the solution using status 'new_to_pending' and adding the $auto object.

function newpost_notify( $auto ) {

  $mailadmin = '[email protected]';
  $subject = 'Subject';
  $headers  = 'MIME-Version: 1.0' . "\r\n";
  $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";    
  $headers .= 'From: xxx <[email protected]>' . "\r\n";
  $message = 'There\'s a new post.';

  wp_mail( $mailadmin, $subject, $message, $headers );
}

add_action( 'new_to_pending', 'newpost_notify', 10, 2 );

thanks to the constructive comments of @Rarst & @flomei

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.