I've setup a custom post type and I want to send an email when I publish a post but I want to use some data from the custom fields I've added to that custom post type, including obtaining an email address from a custom field on my custom post.

I've found some code and can get it to send me an email which all works, including sending the Post Title in the subject, but as soon as I include the get_post_meta, the email doesn't get sent. I've done a lot of reading online to try and find a solution but haven't had any joy, as you can see from my message, I've tried a different option of get_metadata but again this hasn't worked.

One thing I've read is something about the 'transition_post_status' being fired before it's saved the meta data, but I can't find anywhere what I should use instead that still achieves my requirement of only sending an email for a post on the initial publish (I don't want it to send the email more than once).

I'm a complete novice to PHP and everything I've done so far has been through researching/googling to find solutions, so please go easy if this is a really simple solution. Thanks in advance.

add_action( 'transition_post_status', 'wpse_admin_email_once', 10, 3 );
function wpse_admin_email_once( $new, $old, $post ) {
if ( $post->post_type == 'mycustompost' && $new == 'publish' && $old == 'auto-draft' ) {

$emails  = get_post_meta($post->ID, 'email', true);
$headers = 'From: Name <hello@company.co.uk>';
$message = get_metadata('mycustompost', $post->ID, 'message', true);
$subject = wp_strip_all_tags( get_the_title( $post->ID ) );

wp_mail( $emails, $subject, $message, $headers );
  • It may just be easier to trigger the sending of the email during the SAVE process, but check the status of the post for 'publish' before determining whether to send or not, that way you know for sure that you have the post meta available. Oct 20, 2022 at 18:21


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy