Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the wordpress hook when I publish a new post, (not when I update a published one)?

I want to send an email any time a new post is FIRST published (not when it is edited)

I tried:

add_action('publish_post', 'postPublished');

But postPublished is ALSO called when I update an already published post. I just want to get it called ONLY at first time a post is published.

Regards

like image 993
yarek Avatar asked Nov 22 '16 14:11

yarek


2 Answers

I think the hook you're looking for is draft_to_publish

If you are wanting to only send an email on a new post I would consider targeting when the post is published. You could even look at the transition_post_status hook and just conditionalize if the post has been edited, something like this could work:

function so_post_40744782( $new_status, $old_status, $post ) {
    if ( $new_status == 'publish' && $old_status != 'publish' ) {
        $author = "foobar";
        $message = "We wanted to notify you a new post has been published.";
        wp_mail($author, "New Post Published", $message);
    }
}
add_action('transition_post_status', 'so_post_40744782', 10, 3 );
like image 164
DᴀʀᴛʜVᴀᴅᴇʀ Avatar answered Oct 02 '22 03:10

DᴀʀᴛʜVᴀᴅᴇʀ


You should read Post Status Transitions from the WordPress Codex in order to fully understand the problem.

A possible solution which covers most cases for instance is:

add_action('draft_to_publish', 'postPublished');
add_action('future_to_publish', 'postPublished');
add_action('private_to_publish', 'postPublished');
like image 33
Blackbam Avatar answered Oct 02 '22 03:10

Blackbam