Recently I had a situation where I needed to determine if a post type was not one of WordPress’ core types. WordPress has several base post types:
- Post (Post Type: ‘post’)
- Page (Post Type: ‘page’)
- Attachment (Post Type: ‘attachment’)
- Revision (Post Type: ‘revision’)
- Navigation menu (Post Type: ‘nav_menu_item’)
For example, let’s say that we need to render a select field in the backend with all the post types currently registered in WordPress. We’re planning on creating a plugin and we want the user to be able to select a specific post type. So we need to dynamically get the registered post types just in case they have additional custom post types of their own or from a theme or plugin.
WordPress has a core function for this ( get_post_types() ) which will, by default, return an array of post types names or objects.
What you might expect to see is Post, Page, and Attachment from the output of this function. But when you start to render the field, you also get Revision and Navigation menu. Those aren’t post types that we expect the user to need so it would be a good idea to filter them out.
The get_post_types() function takes an array of arguments as its first parameter which we can provide with ‘public’ => true and it will only include the registered post types that have been defined as ‘public’. We can also pass in ‘objects’ as the second parameter to make sure that we get the whole post type object back instead of just the post type name. Using the different labels will be useful when structuring the field.
The revision and nav_menu_item post types are both registered to be private so without them listed, we can render our field.