Last Updated: June 22, 2016
·
11.23K
· felipelavinz

Sanitizing queries with "IN" clauses with $wpdb on WordPress

$wpdb includes the "prepare" method that will sanitize the query based on the type of data used for the search clauses.

Even though there's no straightforward way to sanitize "IN" clauses, you can use a handy workaround. For instance:

// get a set of "special" entries
// $special_entries = array(1, 3, 5, 8, 13, [...]);
$special_entries = get_option('my_special_entries');

// how many entries will we select?
$how_many = count($special_entries);

// prepare the right amount of placeholders
// if you're looing for strings, use '%s' instead
$placeholders = array_fill(0, $how_many, '%d');

// glue together all the placeholders...
// $format = '%d, %d, %d, %d, %d, [...]'
$format = implode(', ', $placeholders);

// and put them in the query
$query = "SELECT ID, post_title, post_name, post_parent FROM $wpdb->posts WHERE post_parent IN($format)";

// now you can get the results
$results = $wpdb->get_results( $wpdb->prepare($query, $special_entries) );

3 Responses
Add your response

awesome! i am glad i found it when i needed it. :)

over 1 year ago ·

Thanks Man !

over 1 year ago ·

Perfect, thank you!

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

WordPress sites collect scripts from themes, plugins, and tag managers. A compromised plugin update can add a skimmer to every page without a change in your own templates.

Security insights from Cside