timothyjensen
6/20/2017 - 3:39 PM

$wpdb->prepare for SQL IN statements

$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;