Wordpress - Only get post types based on support
I found out that get_post_types_by_support()
seems to be the solution to get the desired result:
$post_types = get_post_types_by_support(array('title', 'editor', 'thumbnail'));
The above will return post
, page
and any custom post type that supports title
, editor
and thumbnail
.
Since this will also return private post types, we could loop through the list and check if the type is viewable at the frontend. This can be done by using the is_post_type_viewable()
function:
foreach ($post_types as $key => $post_type) {
if (!is_post_type_viewable($post_type)) {
unset($post_types[$post_type]);
}
}
get_post_types()
accepts an array of arguments to match the fields of a post type object. So, you could do something like this (not tested):
$post_types = get_post_types(array(
'public' => true,
'supports' => array( 'editor', 'title', 'thumbnail' )
), 'objects');
Unfortunately, you can not set someting like "exclude" in this function, and also you get only post types that support exactly 'editor', 'title', 'thumbnail'
, no more and no less.
Or you could use get_post_types_by_support()
(only for WP 4.5 and greater. Also, note that you can not exclude specific post types with this function either, but for the specific case of support for editor, title, thumbnail
, attachment post type will be excluded in most cases).
$post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );
If you want something that will work in any case, I would try to get post types based in a wider criteria, then build your own array, something like this:
$_post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );
$post_types = [];
foreach($_post_types as $post_type) {
// In most cases, attachment post type won't be here, but it can be
if( $post_type->name !== 'attachment' ) {
$post_types[] = $post_type;
}
}