With what hook can I address all posts from all custom post types when they are published?

What about using save_post or wp_insert_post hook, both have

@param     int               $post_ID     Post ID.
@param     WP_Post     $post          Post object.
@param     bool            $update     Whether this is an existing post being updated or not.

as parameters. It is pretty self-explaining that the $update can be used to determine, if it is a new post or not. Additionally you will need to check for is it a custom post type, I use the is_custom_post_type() function by @toscho.

So here we go:

function wpse135423_function_to_call( $post_id, $post, $update ) {
    if ( wp_is_post_autosave( $post_id ) ) {
        return 'do nothing, because it is an autosave';
    }
    if ( wp_is_post_revision( $post_id ) ) {
        return 'do nothing, because it is a revision';
    }
    // if it is an update 
    if ( $update == TRUE ) {
        return 'do nothing, because it is an update';
    }
    // if it is a custom post type 
    if ( is_custom_post_type() == TRUE ) {
        // code to do whatever you want
    }
}
// Do NOT use both hooks!
add_action( 'save_post', 'wpse135423_function_to_call', 10, 3 );
add_action( 'wp_insert_post', 'wpse135423_function_to_call', 10, 3 );

Shortly, only newly created custom post type posts are addressed, while there is no need to know the custom post types name.

Leave a Comment