1

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:

$args=array(
    'public'                => true,
    'exclude_from_search'   => false,
    '_builtin'              => false
); 
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types=get_post_types($args,$output,$operator); 

// 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) ?

3

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',
);
  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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