Wordpress:wp_insert_post()多次触发

时间:2014-08-11 00:13:27

标签: wordpress plugins insert duplicates

我正在构建一个简单的WP插件,它应该创建一个新帖子并为帖子保存一些元数据。我创建了一个具有该功能的函数,暂时将它连接到'init'事件以检查它是否有效。

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';
    }
}

现在,每当我重新加载管理页面时,我都会收到'SUCCESS'消息,我还会在postmeta表中获得4-6个新帖子'Some Post Title'和4-6 * 2个新条目。 'SUCCESS'消息只回显一次,这意味着该函数只运行一次,但我仍然多次将数据插入数据库。我做错了什么?

1 个答案:

答案 0 :(得分:-1)

在插入新帖子之前检查是否已存在。所以 get_page_by_title('Some Post Title')== false 然后只插入新帖子。

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 );
}