Last active
June 20, 2017 15:40
-
-
Save timothyjensen/06263a5e341c2abe2ce74f83912b88af to your computer and use it in GitHub Desktop.
$wpdb->prepare for SQL IN statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$data_types = [ 'data_item_one', 'data_item_two' ]; | |
// Props to @hellofromtonya for this. | |
$data_type_placeholders = implode( ', ', array_fill( 0, count( $data_types ), '%s' ) ); | |
global $wpdb; | |
$query = " | |
SELECT pm.post_id, pm.meta_key, pm.meta_value | |
FROM {$wpdb->postmeta} AS pm | |
WHERE pm.meta_key IN ( {$data_type_placeholders} ) | |
AND pm.meta_value <> '' | |
"; | |
$sql_query = $wpdb->prepare( $query, $data_types ); | |
$results = $wpdb->get_results( $sql_query ); | |
return $results; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment