Tutorial

How to Get the Registered Post Types in WordPress

The function get_post_types returns the post types currently registered in WordPress.

Syntax

get_post_types($args, $output, $operator) filters registered post types according to the value of $args, $output, and $operator; and returns the result in an associative array.

  • $args —array of attributes to filter the registered post types
  • $output —type of output to return, either 'names' or 'objects'
  • $operator —operator to use during the filtering, either 'AND', 'OR', or 'NOT'

By default, $args is an empty array so all post types are returned, and $output is 'names'. Possible values for $operator are below, being 'AND' the default value.

  • 'AND' —select post types that satisfy all attributes in $args
  • 'OR' —select post types that satisfy at least one attribute in $args
  • 'NOT' —select post types that satisfy none of the attributes in $args

Examples

The set of possible attributes to use in $args is large. Each one is documented in detail in the class WP_Post_Type.

// Get the identifier of each registered post type
$example1 = get_post_types();

// Get the object of each registered post type
$example2 = get_post_types(array(), 'objects');

// Get the identifier of the post types that are public
$example3 = get_post_types(array('public' => true));

// Get the object of the post types that are public and hierarchical
$args4 = array('public' => true, 'hierarchical' => true);
$example4 = get_post_types($args4, 'objects');

// Get the identifier of the post types that are public or hierarchical
$args5 = array('public' => true, 'hierarchical' => true);
$example5 = get_post_types($args5, 'names', 'OR');

Common use

This function is frequently used in the administration side of plugins. Suppose that you are developing a plugin that should list all archive-enabled post types to let the user make a choice. Just a line of code is necessary to get these post types.

// Get all post types that have archive
$archive_enabled_types = get_post_types(array('has_archive' => true));

Further reading

I recommend the other tutorials in this series to learn more about post types in WordPress.

Exercise

Get the object of the custom post types that are not hierarchical.

Source code

The source code developed in this tutorial, including a possible answer to the exercise, is available here.

WordPress

Related Tutorials

Open chat
Need help?
Hi! 🤝 Open the chat if you have any question, feedback, or business proposal. I would love to hear from you.