0

I have to insert multiples posts. It will takes time to insert post one by one. Is their any way to insert all posts($array) in one query?

$my_post = array(
                  'post_title'    => $row->title,
                  'post_content'  => $row->content,
                  'post_status'   => 'publish',
                  'post_date_gmt'   => $row->created_at,
                  'post_date'   => $row->created_at,
                  'post_author'   => 1,
                  'post_excerpt'   => 'test',
                  'tags_input'   => $tags,
                  'post_category' => array(1,2)
                );
    wp_insert_post( $my_post );

}
jps
  • 20,041
  • 15
  • 75
  • 79

1 Answers1

0

If you need WordPress to do all the work related to creating a post, there's no easy way of inserting multiple posts in one go, as mentioned in this answer over on wordpress.stackexchange.com. This is because wp_insert_post does quite a lot of things like adding data to the wp_posts and wp_postmeta tables. See the source code for the function for more details.

However, technically, you can do a direct SQL query but it won't add post meta data, sanitize data or run any plugin or theme filters. Here's a template query that you can fill out for each post you wan to create and then run it against the DB with mysqli_query or similar afterwards:

INSERT INTO `wp_posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) VALUES (NULL, '0', '0000-00-00 00:00:00.000000', '0000-00-00 00:00:00.000000', '', '', '', 'publish', 'open', 'open', '', '', '', '', '0000-00-00 00:00:00.000000', '0000-00-00 00:00:00.000000', '', '0', '', '0', 'post', '', '0');

But again, I would recommend against it. One at a time is a little slower but you get a lot additional functionality in return and performance shouldn't be all that bad unless you're adding a very, very large number of posts.

Lasse
  • 1,414
  • 11
  • 19