admin管理员组文章数量:1294325
Is it possible to have something like name__in
array()
for WP_Query
?
I am trying to get a list of custom posts from an array of the post's slugs.
Looking at the codex, there doesn't seem to be a way.
Is it possible to have something like name__in
array()
for WP_Query
?
I am trying to get a list of custom posts from an array of the post's slugs.
Looking at the codex, there doesn't seem to be a way.
Share Improve this question edited Dec 2, 2014 at 6:49 Pieter Goosen 55.4k23 gold badges115 silver badges210 bronze badges asked Jun 13, 2014 at 16:38 BillBill 1331 silver badge6 bronze badges 1 |2 Answers
Reset to default 4The parameter is not supported by WordPress core, but you can implement it using a filter on 'posts_where'
:
// require PHP 5.3+
add_action( 'posts_where', function( $where, $query ) {
if ( isset( $query->query['name__in'] ) && is_array( $query->query['name__in'] ) ) {
global $wpdb;
$names = array_filter( array_map( function( $name ) use( $wpdb ) {
$sane = sanitize_title( $name );
return ! empty( $sane ) ? $wpdb->prepare( '%s', $sane ) : NULL;
}, $query->query['name__in'] ) );
if ( ! empty( $names ) ) {
$where .= " AND {$wpdb->posts}.post_name IN (" . implode( ',', $names ) . ")";
}
}
return $where;
}, PHP_INT_MAX, 2 );
Note that this will not work by default using get_posts
because using that function sql filters are suppressed by default and you need to enable it using 'suppress_filters' argument:
This will work:
$args = array(
'post_type' => 'my-cpt',
'name__in' => array( 'foo', 'bar' )
);
$posts = new WP_Query( $args );
This will not work:
$args = array(
'post_type' => 'my-cpt',
'name__in' => array( 'foo', 'bar' )
);
$posts = get_posts( $args );
This will work too:
$args = array(
'post_type' => 'my-cpt',
'name__in' => array( 'foo', 'bar' ),
'suppress_filters' => FALSE // <== enable filters
);
$posts = get_posts( $args );
As of 2021 and adding to gmazzap's Answer:
the parameter should be 'post_name__in', see https://developer.wordpress/reference/classes/wp_query/#post-page-parameters
$args = array(
'post_type' => 'my-cpt',
'post_name__in' => array( 'foo', 'bar' )
);
$posts = new WP_Query( $args );
本文标签: wp queryWPQuery and namein
版权声明:本文标题:wp query - WP_Query and name__in 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741599533a2387615.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
name__like
. – birgire Commented Jun 13, 2014 at 17:04