我需要使用SQL查询所有帖子(尝试使用WP_Query
工作不正常),属于某些岗位类型
$post_types = get_post_types();
unset( $post_types[\'attachment\'], $post_types[\'nav_menu_item\'] );
$post_type_string = \'\\\'\' . implode( \'\\\', \\\'\', $post_types ) . \'\\\'\';
global $wpdb;
$replace_query = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_type IN ( %s )", $post_type_string ), ARRAY_A );
The
$post_types
数组会给我
array( \'post\' => \'post\', \'page\' => \'page\', \'revision\' => \'revision\', \'custom_css\' => \'custom_css\', \'attachment\' => \'attachment\', \'nav_menu_item\'=> \'nav_menu_item\', \'customize_changeset\' => \'customize_changeset\', \'tt_font_control\' => \'tt_font_control\' )
我内爆了这个数组,在值周围添加引号,并将其放入
$wpdb->prepare
如图所示,但我得到的只是空数组。
当我取下prepare并执行此操作时
$replace_query = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_type IN ( $post_type_string )", ARRAY_A );
查询成功了,我得到了完整的数组。
为什么会这样?
这个$post_type_string
是字符串,所以%s
在准备中是正确的。
我试图不“引用”字符串中的值,但效果不太好,我尝试了双引号。我知道prepare
$query = str_replace( "\'%s\'", \'%s\', $query ); // in case someone mistakenly already singlequoted it
$query = str_replace( \'"%s"\', \'%s\', $query ); // doublequote unquoting
$query = preg_replace( \'|(?<!%)%f|\' , \'%F\', $query ); // Force floats to be locale unaware
$query = preg_replace( \'|(?<!%)%s|\', "\'%s\'", $query ); // quote the strings, avoiding escaped strings like %%s
array_walk( $args, array( $this, \'escape_by_ref\' ) );
return @vsprintf( $query, $args );
}
从…起developers prepare docs. 这是不是因为引用?如果是这样,如何正确准备我的查询?
EDIT:
这个
WP_Query
这不符合预期
$temp_posts = new WP_Query( array(
\'post_type\' => $post_types,
\'posts_per_page\' => 1000000,
\'no_found_rows\' => true,
\'post_status\' => array( \'any\', \'draft\' )
)
);
最合适的回答,由SO网友:cybmeta 整理而成
您可以直接使用数组,因为$wpdb->prepare()
method can be called like vsprintf()
, 哪一个works like sprintf()
but accepts arrays of arguments.
$post_types = get_post_types();
unset( $post_types[\'attachment\'], $post_types[\'nav_menu_item\'] );
global $wpdb;
$replace_query = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_type IN ( %s )", $post_types ), ARRAY_A );
代码的问题是,您会得到如下字符串:
"\'page\', \'attachment\', \'revision\', \'custom_css\', \'customize_changeset\'"
所以
IN
您得到的声明如下:
IN ( "\'page\', \'attachment\', \'revision\', \'custom_css\', \'customize_changeset\'" )
而不是正确的字符串数组:
IN ( \'page\', \'attachment\', \'revision\', \'custom_css\', \'customize_changeset\' )