Wordpress: wp_insert_post() firing multiple times

2019-08-31 09:28发布

问题:

I'm building a simple WP plugin that's supposed to create a new post and save some meta for the post. I created a function with the functionality and for the time being I hooked it to the 'init' event to check if it works.

add_action( 'init', 'my_func' );

function my_func() {

    $my_post = array(
        'post_title'    => 'Some Post Title',
        'post_name'     => 'some-post-title',
        'post_type'     => 'custom-post-type',
        'post_status'   => 'publish'
    );

    $inserted_post_id = wp_insert_post($my_post);

    if($inserted_post_id != 0) {
        add_post_meta($inserted_post_id, 'some-key', 'some-value');
        add_post_meta($inserted_post_id, 'some-other-key', 'some-other-value');
        echo 'SUCCESS';
    } else {
        echo 'ERROR';
    }
}

Now, whenever I reload the admin page, I get the 'SUCCESS' message echoed out, and I also get 4-6 new post called 'Some Post Title', and 4-6*2 new entries in the postmeta table. The 'SUCCESS' message echoes only once, meaning the function runs only once, still I get the data inserted to the database multiple times. What am I doing wrong?

回答1:

Check before going to insert new post if already exists or not. So get_page_by_title('Some Post Title') == false then only insert new post.

add_action( 'init', 'my_func' );

function my_func()  {
$my_post = '';
if( get_page_by_title('Some Post Title','OBJECT','custom-post-type') == NULL )
$my_post= array(
        'post_title'    => 'Some Post Title',
        'post_name'     => 'some-post-title',
        'post_type'     => 'custom-post-type',
        'post_status'   => 'publish'
);
wp_insert_post( $my_post );
}