Post publish only hook?

Is there any hook which is fired only when the post is “published” for the first time.

I dont want to execute my code when the post is “updated” or when its status is set to “not-published” and then “published” again.

Read More

EDIT:

add_action('draft_to_published','func_tion');

function func_tion($post){
    $post_id = $post->ID;   

    if ( !get_post_meta( $post_id, 'mycoderan', $single = true ) )
    // run code to manipulate data
    wp_enqueue_script('plugin_name',plugin_dir_url(__FILE__ ).'script.js');
    $params = array() // set parameters
    wp_localize_script('plugin_name', 'params', $params );
    update_post_meta( $post_id, 'mycoderan', true );
}

Related posts

Leave a Reply

1 comment

  1. The {$old_status}_to_{$new_status} and {$new_status}_{$post->post_type} hooks tend to generally solve the problem.

    To avoid running the code in case post status is changed to draft then published again (after already being published), implement a simple flag using the post_meta functionality.

    Note: the updated hook should be ‘draft_to_publish’ instead of ‘draft_to_published’ however, the code below is not modified and should be if you plan to use in WP 3.5

    add_action( 'draft_to_published', 'wpse47566_do_once_on_publish' );
    function wpse47566_do_once_on_publish( $post ) {
        // check post type if necessary
        if ( $post->post_type != 'a_specific_type' ) return;
    
        $post_id = $post->ID;
    
        if ( !get_post_meta( $post_id, 'mycoderan', $single = true ) ) {
            // ...run code once
            update_post_meta( $post_id, 'mycoderan', true );
        }
    }