In PHP 5.5 you had the function


and I always did


to secure against SQL-Injection.

With PHP 7 mysql_real_escape_string() is gone. An alternative is


but that function needs a link to the mysqli object. When using WordPress to perform a query like this:

$query_args = array( 's' => $_POST['search'] ); $query = new WP_Query( $query_args );

I can't provide a mysqli object. So Do I have to leave all the security stuff to WordPress? Is it enough to do:

$query_args = array( 's' => htmlspecialchars( $_POST['search'] ) ); $query = new WP_Query( $query_args );


  • your code didn't add any security, no point in trying to maintain it. – Mark Kaplun Sep 21 '16 at 8:41
  • What do you mean? – SVARTBERG Sep 21 '16 at 8:42
  • Wordpress API does proper escaping, all you have done is to "break" the actual data that needed to be acted upon – Mark Kaplun Sep 21 '16 at 8:43
  • So if I understand correctly, the answer to my question is that I can do: $query_args = array( 's' => $_POST['search'] ); $query = new WP_Query( $query_args ); – SVARTBERG Sep 21 '16 at 9:01
  • yes, wp_query will do whatever is the needed sanitization to access the DB. To display you might need to do some escaping – Mark Kaplun Sep 21 '16 at 10:39

Maybe you could try this, to sanitize the whole $_POST array


Or to sanitize just a field, you could use the native WP function

$sanitized = sanitize_text_field ( $_POST['key'] );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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