Skip to content
Advertisement

wp_after_insert_post not triggering

I am trying to send an email after a new post has been created. It needs to be sent after the creation of the post, because I want to include the post category in the email. wp_after_insert_post does not seem to work, as no email is sent. I have tried using the same code with the publish_post hook instead, which does send an email correctly, but I am then unable to use the category name in the email.

function new_post_email( $post_id ) {        
    $categories = get_the_category( $post_id );
    $subject = $categories[0]->name;

    $sent = wp_mail($to = 'my@email.com', $subject, $message = 'Test message');
};
add_action( ' wp_after_insert_post', 'new_post_email');

Is there any solution for this? Thanks in advance

Advertisement

Answer

It’s possible your wp_mail() function syntax is incorrect, you also have an extra space in your add_action(). I’ve not seen documentation or examples where you can assign variables a value in the function itself. I would try either declaring your variables outside the function, like so:

function new_post_email( $post_id ) {        
    $categories = get_the_category( $post_id );
    $subject = $categories[0]->name;
    $to = 'myemail.com';
    $message = 'Test message';

    $sent = wp_mail($to, $subject, $message);

};
add_action( 'wp_after_insert_post', 'new_post_email'); // remove space in wp_after_insert...

Or just put the values directly in that don’t have declared vars for:

function new_post_email( $post_id ) {        
    $categories = get_the_category( $post_id );
    $subject = $categories[0]->name;

    $sent = wp_mail('my@email.com', $subject, 'Test message');
};
add_action( 'wp_after_insert_post', 'new_post_email'); // remove space in wp_after_insert...
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement