Wordpress - db_insert_error when using insert_post
I got a similar problem today so I'll share what lead me to the solution (the solution might be different for you, but the way will help).
I got the same error message with absolutely no helpful text, so I dug into the WordPress source code and started debugging.
The error is thrown in only one place in wp_insert_post()
, when $wpdb->insert()
returns false:
if ( false === $wpdb->insert( $wpdb->posts, $data ) ) { if ( $wp_error ) { return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error); } else { return 0; }}
$wpdb->insert()
makes some sanity checks before doing the insert, using process_fields()
in wp-includes/wp-db.php
.
protected function process_fields( $table, $data, $format ) { $data = $this->process_field_formats( $data, $format ); if ( false === $data ) { return false; } $data = $this->process_field_charsets( $data, $table ); if ( false === $data ) { return false; } $data = $this->process_field_lengths( $data, $table ); if ( false === $data ) { return false; } $converted_data = $this->strip_invalid_text( $data ); if ( $data !== $converted_data ) { return false; } return $data;}
I started adding var_dump($data)
between each check and the following if-clause to see where the error came from.
In my case the problem was after the strip_invalid_text()
call, which lead me to the cause of my problem:
I was reading the data to insert from a different database and it came in the wrong encoding. After adding charset=utf8mb4
to my PDO constructor all data was in utf8 and the wp_insert_post()
worked instantly.
It is hard to say what caused the problem in your case, it could be a wrong charset, a wrong format, a field that's too long ... WordPress doesn't really discloses what's the problem. To find it you really have to look closely.
I had a similar problem and the cause of it was that the post_status
parameter was more than 20 characters long.
https://codex.wordpress.org/Post_Status
Hope it helps!
Make sure the encoding of the data being updated matches. In my case I needed to convert ISO-8859-1 data into UTF-8 multibyte on the array you pass to wp_update_post or wp_insert_post
$post_update_array = array('ID' => $post_id,'post_title' => mb_convert_encoding($post->post_title, 'UTF-8', 'auto'),'post_content' => mb_convert_encoding($post->post_content, 'UTF-8', 'auto'),'post_category' => $categories_ids
);