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) );
Written by Felipe Lavín Z.
Related protips
3 Responses
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
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#