Trigger action when new post is insert in wordpres

2020-07-24 05:09发布

问题:

My question is,

Is there any filter or action that trigger when new post is insert in database..?

The reason behind it is I want to add key in post meta when new post is insert from admin side.

I got Action called "save_post" but after refer link .This action trigger in created and update post. but I only want to add meta key when post is created not at update time

回答1:

You can use wp_insert_post so you will get post_id as soon as post inserted and you can then use that to add meta_key.

If you are not using wp_insert_post and want to use action then you can simply put below code :

if ( wp_is_post_revision( $post_id ) )
    return;

which means that if you are updating the post, then it will return back from function.

EDITED

Method-1 to achieve it.

You can simply check with the get_post method that post is there or not.something like below:

add_action('save_post', 'check_for_post_in_database');
function check_for_post_in_database($post_id) {
    //check if the post is in the database or not with get_post( $post_id ) == null 
    if( get_post( $post_id ) == null ) {
        //your code to add meta
    }
}
//You can do same thing with publish_post

Method-2 to achieve it.

add_action('publish_post', 'check_for_meta_in_database');
function check_for_meta_in_database($post_id) {
    global $wpdb;
    $your_meta = get_post_meta($post_id, 'meta_key', true);
    if( empty( $your_meta ) && ! wp_is_post_revision( $post_id ) ) {
        update_post_meta($post_id, 'meta_key', 'meta_value');
    }
}

But as you said there are many meta there, this method will be bit long.

Method-3 to achieve it.

You can do as rnevius suggested which is the one even I would opt. Its like :

add_action( 'transition_post_status', 'check_transition_and_then_add_meta', 10, 3 );
function check_transition_and_then_add_meta( $new_status, $old_status, $post ) { 
    if ( ( 'draft' === $old_status || 'auto-draft' === $old_status ) && $new_status === 'publish' ) {
        add_post_meta($post->ID, 'your_meta_key', 'your_meta_value');
    }
}

or else you can do it with draft_to_publish like:

//as rnevius suggested {$old_status}_to_{$new_status}
add_action( 'draft_to_publish', 'add_meta_when_status_change' );
function add_meta_when_status_change() { 
     add_post_meta($post->ID, 'your_meta_key', 'your_meta_value');
}

You can refer codex for more information about post transition.



回答2:

You're looking for draft_to_publish.

An {old_status}_to_{new_status} action will execute when a post transitions from {old_status} to {new_status}. The action is accompanied by the $post object.



标签: wordpress