I am studying how to write more secure WordPress code by implementing validation, sanitization and data escaping wherever necessary. Validation and escaping makes perfect sense, but I am a little confused about sanitization.

If I use a function like add_post_meta, does this function do sanitization for me? What about set_option or other ones that interact with the database. I usually interact with the database via these functions. In which situations do I need to worry about sanitization myself?

  • 2
    You're talking about SQL sanitising correct?
    – Tom J Nowell
    Jan 19, 2017 at 12:11
  • Yes, preparing data to be stored inside the database. Jan 19, 2017 at 12:16
  • 2
    This should answer your question - stackoverflow.com/questions/16122790/… Jan 19, 2017 at 12:23
  • Thank you! I'm going through several articles on this topics right now and most of them use code examples that validate and sanitize input before passing it to one of these functions. Does that mean that is unnecessary? Jan 19, 2017 at 12:27

1 Answer 1


Yes, WordPress will sanitise data on its way to the database, so long as you use the APIs.

If you're using the wpdb object however you'll need to use the prepare method to sanitise. I recommend against writing SQL queries as it bypasses object caches etc, but if you must write your own SQL, use wpdb to prepare and execute it

For calls such as WP_Query, get_posts, add_post_meta etc etc sanitisation occurs

Note that this is purely DB sanitisation, any additional sanitisation or validation you require, such as trimming trailing spaces, validation of URLs, stripping tags, escaping, etc, must all be done in your code

  • 1
    @MauroBringolf great :) if you could mark it as the correct answer?
    – Tom J Nowell
    Jan 19, 2017 at 16:00

Your Answer

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

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