php – WP_Query by an array or list of post slugs-ThrowExceptions

Exception or error:

Is this possible, I couldn’t find the question asked anywhere on the web.

If you had a list of posts by their slug, example:

$postslugs = array("page-one","page-two","page-three"); 

And you wanted to create a single query to find all these specific pages:

$args=array(  
'post__not_in' => array($post->ID),  
'posts_per_page'=> -1,
'post_type' =>      'customtype',
'post_status' =>    'publish',
'pagename' => $postslugs
);

$my_query = new wp_query( $args ); 

The result should come back with the three pages. This of course would not work the way it’s written now. Is this possible?

How to solve:

If you take a look at the documentation for the WP_Query() class, specifically the Post & Page Parameters section, you’ll see it has a handy parameter called post_name__in which takes an array of post_name (aka slugs). Also, are you sure you need to use post__not_in (and maybe posts_per_page since you’re defining an array of slugs to get already?

$names = array( 'page-one', 'page-two', 'page-three' ); 

$query_args = array(  
    'posts_per_page' => -1,
    'post_type'      => 'customtype',
    'post_status'    => 'publish',
    'post_name__in'  => $names
);

$my_query = new WP_Query( $query_args );

Leave a Reply

Your email address will not be published. Required fields are marked *