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)
?
Instead of creating a string try creating an array and check.
And then form the query as follows