WordPress.org

Ready to get started?Download WordPress

Codex

Plugin API/Action Reference/publish post

WARNING: This hook has been replaced by {$new_status}_{$post_type}.

Description

publish_post is an action triggered whenever a post is published, or if it is edited and the status is changed to publish.

This only gets triggered on posts. For pages you have to use the publish_page action. (WARNING: the publish_page hook seems to never fire on v2.3 and higher. It appears to work as of 2.6. Consider using the 'transition_post_status' hook instead. (See also Post Status Transitions))

Example

The example below will send an email to the post author when his article is published (would be useful for notifying the post author when their post needs to be reviewed before being published).

<?php

// SEND EMAIL ONCE POST IS PUBLISHED

function notify_new_post($post_id) {
    if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) {
        $post = get_post($post_id);
        $author = get_userdata($post->post_author);
        $author_email = $author->user_email;
        $email_subject = "Your post has been published.";

        ob_start(); ?>

        <html>
            <head>
                <title>New post at <?php bloginfo( 'name' ) ?></title>
            </head>
            <body>
                <p>
                    Hi <?php echo $author->user_firstname ?>,
                </p>
                <p>
                    Your post <a href="<?php echo get_permalink($post->ID) ?>"><?php the_title_attribute() ?></a> has been published.
                </p>
            </body>
        </html>

        <?php

        $message = ob_get_contents();

        ob_end_clean();

        wp_mail( $author_email, $email_subject, $message );
    }
}

add_action( 'publish_post', 'notify_new_post' ); ?>