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.
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 );
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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 );
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0