使用IN operator 对于阵列。
使用时$wpdb->prepare()
不必在字符串占位符周围使用引号%s
. 字符串占位符将自动引用。这也是使用时必须采取预防措施的原因$wpdb->prepare()
如果数组值是字符串,则使用IN运算符。
第一个示例不使用post stati的占位符,而是直接将它们(逗号分隔并引用)插入查询字符串中
function get_meta_values( $key = \'\', $type = \'post\', $status = array( \'publish\', \'draft\' ) ) {
global $wpdb;
if ( empty( $key ) ) {
return;
}
// escape the status values
$status = array_map( \'esc_sql\', (array) $status );
// $status_string: a comma separated string with quoted post stati
// $status_string = "\'publish\', \'draft\'";
$status_string = "\'" . implode( "\', \'", $status ) . "\'";
$query = "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = \'%s\'
AND p.post_status IN ( $status_string )
AND p.post_type = \'%s\'";
$r = $wpdb->get_col( $wpdb->prepare( $query, $key, $type ) );
return $r;
}
第二个示例使用此答案中的方法转换数组
https://stackoverflow.com/a/10634225function get_meta_values( $key = \'\', $type = \'post\', $status = array( \'publish\', \'draft\' ) ) {
global $wpdb;
if ( empty( $key ) ) {
return;
}
// $status_string: a comma separated string with string placeholders (%s)
// $status_string = "%s, %s";
$status_string = implode( \', \', array_fill( 0, count( $status ), \'%s\' ) );
//parameters array for call_user_func_array callback function $wpdb->prepare
$prepare = array();
// the query is the first parameter
$prepare[] = "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = %s
AND p.post_status IN ($status_string)
AND p.post_type = %s
";
// from here on out add to the $prepare array in the same order as inside the query
$prepare[] = $key;
foreach ( $status as $s ) {
$prepare[] = $s;
}
$prepare[] = $type;
// calling $wpdb->prepare() with the $prepare array
$query = call_user_func_array( array( $wpdb, \'prepare\' ), $prepare );
$r = $wpdb->get_col( $query );
return $r;
}
注意:如果在生产中使用,这两个示例的编码都应该更加防御性(is\\u array()等)。