WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to query only custom posts types - that is all post types in my WP install excluding posts and pages. I have used get_post_types to build a string of all custom post types which I want to query:

    'public'                => true,
    'exclude_from_search'   => false,
    '_builtin'              => false
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'

// Loop thru the cpts and assign a related taxonomy to a variable
$posttypes_array = "";
foreach ($post_types  as $post_type ) {
    $posttypes_array .= "$post_type, ";
$posttypes_array = rtrim($posttypes_array, ', ');
echo $posttypes_array;

The output for the variable $posttypes_array is this string:

'puzzles', 'quizzes', 'challenges', 'tales', 'can_you_help'

My issue is that I can't use this variable to query all of these post types like this:

$buildArgsAllQuestions = array( // Add out new query parameters
    'post_type' => array($posttypes_array),
    //'post_type' => $posttypes_array,
    'orderby' => 'date',
    'order' => 'DESC',

My query for all custom posts only works when I use this line for post_type:

'post_type' => array( 'puzzles', 'quizzes', 'challenges', 'tales', 'can_you_help' ),

Can anyone tell me how I can use the variable $posttypes_array or something similar to query all custom posttype like this: 'post_type' => array($posttypes_array) ?

share|improve this question
up vote 2 down vote accepted

Instead of creating a string try creating an array and check.

$posttypes_array = array();
foreach ($post_types  as $post_type ) {
    $posttypes_array[] = $post_type;

And then form the query as follows

$buildArgsAllQuestions = array( // Add out new query parameters
    'post_type' => $posttypes_array,
    //'post_type' => $posttypes_array,
    'orderby' => 'date',
    'order' => 'DESC',
share|improve this answer
Yep - this worked perfectly, I'll go away and ready up on setting up and using arrays effectively - thanks Joshua! – Bassscape Jul 23 '12 at 9:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.