I'm working on a custom search page and I usually use wpdb->prepare when crafting custom queries. But this time I went with get_posts to create the below query. But I'm wondering if I have to worry about SQL Injection with it. Should I? Or does get_posts() have that security built in?

If not, how do I clean the incoming variables?

$SEARCH_QUERY = @$_GET['s2'];

$args2 = array(
    'orderby'          => 'date',
    'order'            => 'DESC',
    's'                => $SEARCH_QUERY

$arrSearchResults = get_posts($args2);

echo "<pre>";
echo "</pre>";
  • I'd advise using WP_Query instead. get_posts won't fire post loop lifecycle events, and by default it does not use caches to avoid performance hits. As for a custom search page, you don't need to do this. The standard search page with a standard loop works just fine if you append query variables to the URL, e.g. mysite.com/?s=test&post_type=test will search all posts of type test for the string test, likewise if I had a hidden input in my search form named post_type
    – Tom J Nowell
    Aug 10, 2020 at 13:16
  • Also, you used the @ operator, do not use that operator. It does not fix or swallow errors, it just hides the message from the error log, the error stll happens. Use if ( ! empty( $_GET['s2'] ) { and check if it exists instead of blindly accessing it
    – Tom J Nowell
    Aug 10, 2020 at 13:18
  • So you're saying that get_posts does not properly sanitize variables and provides no protection against SQL Injection?
    – Taurian
    Aug 10, 2020 at 15:19
  • I said nothing about SQL injections and get_posts parameters, these are the comments not the answers. @ is extreme bad practice. Avoid the PHP warning by checking if the array actually has a h2 parameter, don't just silence it
    – Tom J Nowell
    Aug 10, 2020 at 15:58

1 Answer 1


If not, how do I clean the incoming variables?

In most cases you don't, get_posts calls WP_Query internally, and WP_Query performs some sanitization, namely via wpdb->prepare.

However, for what you're trying to do, this is the wrong approach. Just use a standard search.php template with a standard post loop, and use input fields that have the same names as the parameters for WP_Query. WP will automatically filter as a result of them being added to the URL. There is no need for a custom page template with a custom query and custom URL parameters. It's just unnecessary complexity, and double the database queries ( don't forget the broken pagination, dealing with 404's, etc )

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.