Since while I was doing research I stumbled accross this thread, but it didn't bring me to the result I wanted. So I decided to register here to point out my approach to aquire the need of fetching posts with multiple post types.
1st) I registered a new RestAPI Endpoint to get the ability to query multiple post types:
//PHP
add_action( 'rest_post_query', function( $args, $request ){
$post_types = $request->get_param( 'type' );
if( ! empty( $post_types ) ){
if( is_string( $post_types ) ){
// filtering posttypes, seperated with comma into an array, ignoring square brackets
$post_types = explode( ',', str_replace( array( '[', ']') , '', $post_types ) );
foreach ( $post_types as $key => $post_type ){
$object = get_post_type_object( $post_type );
if( ! $object || ! $object->show_in_rest ){
unset( $post_types[ $key ] );
}
}
}
$args[ 'post_type' ] = $post_types;
} else {
// fallback: no type defined, return post as default
$args[ 'post_type' ] = 'post';
}
return $args;
}, 10, 2 );
Check your new API endpoint easily by calling it with your browser
https://*yoururl.com*/wp-json/wp/v2/posts?per_page=10&categories=0&type=posts,page
I don't use the Gutenberg function getEntityRecords anymore to fetch posts. I choose that way performance wise to avoid multiple calls of getEntityRecords.
2nd) In my Gutenberg block I created a hook to call:
export default function useFetchPosts( url ) {
const [data, setData] = useState( null );
useEffect(() => {
async function loadData() {
const response = await fetch( url );
if(! response.ok ) {
return false;
}
const posts = await response.json();
setData(posts);
}
loadData();
}, [url]);
return data;
}
3rd) to get the posts I just call it like this inside my edit block:
// parsedCategories and
// parsedPostTypes have to set and parsed by you before ofcourse ;)
const numberposts = 10;
const postFields = '&_fields=id,author,link,title,_links';
const posts = useFetchPosts( 'https://'+window.location.host+'/wp-json/wp/v2/posts?per_page='+numberposts+'&categories='+parsedCategories+'&_embed=author&type='+parsedPostTypes+'&orderby=date&order=desc'+postFields );
Check out the restAPI reference for available args and parms:
https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/
Cheers