Does wp_insert_post validate the input?

The short answer; absolutely.

wp_insert_post() will only SQL escape the content. Use the KSES library & wp_kses() to filter out the nasties, or esc_html() to escape all HTML.

Most importantly, check out the codex on data validation (read: sanitization).

A Note On KSES: Use wp_filter_kses() or wp_kses_data() to apply the same KSES rules as post comments. The subtle difference between the two is the former expects data escaped with slashes (and returns the same), whilst the latter does not.

WordPress (bizarrely) enforces magic quotes, so $_POST, $_GET (and the like) will have escape slashes added by default.

A Note On wp_insert_post(): This function also expects the data array to have slashes added, so you’ll need to sanitize it with add_magic_quotes() if that’s not the case.

Update: And put in practice;

$_POST['post_title'] = wp_filter_nohtml_kses( $_POST['post_title'] ); // also expects & returns slashes
$_POST['post_content'] = wp_filter_kses( $_POST['post_content'] );

$post_ID = wp_insert_post( $_POST );

// add to the fun - wp_update_post() will add slashes if $postdata is an object!
$update = ( object ) stripslashes_deep( array( 'ID' => $post_ID ) + $_POST );
$update->post_title .= ' Updated!';
wp_update_post( $update )

Leave a Comment