Skip to content

Instantly share code, notes, and snippets.

@timothyjensen
Last active June 20, 2017 15:40
Show Gist options
  • Save timothyjensen/06263a5e341c2abe2ce74f83912b88af to your computer and use it in GitHub Desktop.
Save timothyjensen/06263a5e341c2abe2ce74f83912b88af to your computer and use it in GitHub Desktop.
$wpdb->prepare for SQL IN statements
<?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