Only get post types based on support

I am trying to retrieve a list including both builtin and custom post types:

$post_types = get_post_types(array(
  'public' = TRUE,
), 'objects');

The above almost works, but I would like to exclude the attachment from this list, only returning post types with specific support such as editor, title and thumbnail. Is this possible?

Topic post-type-support custom-post-types Wordpress

Category Web


The simplest approach for the OP's question would be to just unset 'attachment' from the returned array;

$post_types = get_post_types(array('public' => TRUE,), 'objects');
unset($post_types['attachment']);

While not as elegant as the other solutions it has the least overhead.


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;
    }
}

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]);
  }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.