Wordpress: wp_insert_post() firing multiple times

穿精又带淫゛_ 提交于 2019-12-12 05:39: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 );
}


来源:https://stackoverflow.com/questions/25234254/wordpress-wp-insert-post-firing-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!