正如你在source code 这个=
符号在中硬编码wpdb::update()
方法,因此,默认情况下not 可能使用IN
用于更新方法。
最简单的方法是使用wpdb::query()
使用sql查询时,只需确保正确地转义所有值
示例:
function wpdb_update_in( $table, $data, $where, $format = NULL, $where_format = NULL ) {
global $wpdb;
$table = esc_sql( $table );
if( ! is_string( $table ) || ! isset( $wpdb->$table ) ) {
return FALSE;
}
$i = 0;
$q = "UPDATE " . $wpdb->$table . " SET ";
$format = array_values( (array) $format );
$escaped = array();
foreach( (array) $data as $key => $value ) {
$f = isset( $format[$i] ) && in_array( $format[$i], array( \'%s\', \'%d\' ), TRUE ) ? $format[$i] : \'%s\';
$escaped[] = esc_sql( $key ) . " = " . $wpdb->prepare( $f, $value );
$i++;
}
$q .= implode( $escaped, \', \' );
$where = (array) $where;
$where_keys = array_keys( $where );
$where_val = (array) array_shift( $where );
$q .= " WHERE " . esc_sql( array_shift( $where_keys ) ) . \' IN (\';
if( ! in_array( $where_format, array(\'%s\', \'%d\'), TRUE ) ) {
$where_format = \'%s\';
}
$escaped = array();
foreach( $where_val as $val ) {
$escaped[] = $wpdb->prepare( $where_format, $val );
}
$q .= implode( $escaped, \', \' ) . \')\';
return $wpdb->query( $q );
}
然后像这样使用:
wpdb_update_in(
\'posts\', // table
array( \'post_author\' => \'1\', \'post_status\' => \'draft\' ), // data
array( \'post_author\' => array( \'2\', \'3\', \'4\', \'5\' ) ), // where
array( \'%d\', \'%s\' ), // format
\'%d\' // where format
);
执行的SQL将是
UPDATE wp_posts
SET post_author = 1, post_status = \'draft\'
WHERE post_author IN (2, 3, 4, 5)