Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

If I use the wp_insert_post in a plugin, will I have to check the content for SQL injection problems and XSS or will the wp_insert_post function do this for me?

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

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 )
share|improve this answer
    
+1 for the explanation. So if I understood you right, if the data passed to the wp_insert_post comes from $_POST, then I don't have to do anything because escape slashes are added by default. Am I correct? –  Can't Tell May 16 '11 at 11:46
    
Yup - I posted a snippet for clarity :) –  TheDeadMedic May 16 '11 at 13:18
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.