Looking at the Codex for wp_insert_post() it states that this function "...sanitizes variables, does some checks, fills in missing variables like date/time, etc. " (EDIT: I updated the Codex entry to include a more robust example that includes security as well as post meta and category assignment)

Just wondering whether I need to do any further sanitization to prevent XSS hacks and the like or whether enough is being done through the function.

To be honest, I've checked through the function in core and haven't found any wp_kses() or other sanitization on post_content for example, so I'm a little concerned. All I can see that it does is stripslashes_deep() on the data.

So should I be running wp_kses() or anything else when I build my arguments to wp_insert_post()?

What's the best practice here? The Codex is pretty cavalier about security in its example.


  • 2
    It only prevents SQL injection. If you want to run kses on the content, you'll have to do it yourself. WP can't guess what HTML to strip out. What if the post is submitted by an admin, and he wants to insert a <script> inside it? Jul 29, 2011 at 16:09
  • 1
    Okay, good to know. wp_kses_post() on everything then and wp_kses_title() on the title!
    – Tom Auger
    Aug 1, 2011 at 2:57
  • Updated the Codex to show an example of data validation and wp_insert_posts().
    – Tom Auger
    Aug 23, 2011 at 14:49

1 Answer 1


You don't have to do anything.

On WP load:

'init' hook -> kses_init() -> kses_init_filters()


wp_insert_post() -> sanitize_post() -> sanitize_post_field() -> 'content_save_pre' -> wp_filter_post_kses()

Similarly for post titles, comment text etc.

Conclusion: wp_insert_post() is very sanitized. :)

  • Thanks Scribu for that correction - definitely a better way to go! Though I wish you hadn't scrapped that entire code snippet, because it was also a good illustration of other aspects of using wp_insert_post() that the main example doesn't cover.
    – Tom Auger
    Aug 23, 2011 at 18:35
  • Yeah, felt kind of bad about that too. However, it was beyond the scope of wp_insert_post(). A separate, top-to-bottom tutorial would be better, I think.
    – scribu
    Aug 23, 2011 at 19:01
  • Updated answer and codex as well.
    – scribu
    Aug 23, 2011 at 21:33
  • lol @ latest edit. sometimes it takes some digging to find all the gold already buried inside core :) I lost the thread when I was tracing it back. Looks like you're a better sleuth than I! Thanks for sticking with this, and updating the codex.
    – Tom Auger
    Aug 24, 2011 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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