How to get a list of all post types in WordPress

To retrieve custom post types in WordPress, you can use the get_post_types function. Here's an example:

$args = ['public' => true, '_builtin' => false];
$custom_post_types = get_post_types($args, 'objects');

foreach ($custom_post_types as $post_type) {
    echo $post_type->name . '<br>';
}

This code snippet gets all custom post types that are public and not built-in (i.e., not default post types like 'post' or 'page') and then prints their names. You can customize the parameters in the get_post_types function based on your specific requirements.

In this blog post, I will demonstrate how to create a custom post type filter for querying posts in WordPress using a <select> tag with the onchange event.

Additionally, instead of including all of them (post types) in the query, I would prefer a query with specific custom post types only.

method 1: Get post type dynamically

In WordPress, the get_post_types function retrieves an array of registered post types. You can use this function to obtain a list of all post types, or you can pass specific parameters to filter the results. Here's an example

/* To get all post types */
$post_types = get_post_types();

/* Exclude built-in types */
$args = array(
    'public' => true,
    'exclude_from_search' => false,
);
$post_types = get_post_types($args, 'objects'); // For post type name only, use 'names' instead of 'objects'.

/* Follow to exclude specific types from post_type list. */
$exclude_types = array('page', 'attachment', 'event', 'news');
$post_types    = array_diff($post_types, $exclude_types); 

foreach ($post_types as $post_type) {
    echo 'Custom Post Type: ' . $post_type->name . '<br>';
}

method 2: Create custom post type array

Creating an array to display only the desired post type name is a straightforward method. However, it's important to set the name exactly as the post type name, as the query is case-sensitive.

$post_types = ['blog','ebook','case-study','podcast','video','webinar']; 

foreach ($post_types as $post_type) {
    echo 'Custom Post Type: ' . $post_type . '<br>';
}

Create custom post type filter:

If you want to create custom post type filter for your feeds page.

<div class="select-wrapper">
  <select id="post_type">
    <option selected>All Posts</option>
    <?php foreach ($post_types as $post_type):
      $post_slug = ($post_type == 'blog') ? 'post' : $post_type; // Blog refers to posts ?>
      <option custom_attribute="<?= $post_slug ?>"> <?= $post_type;?> </option>
    <?php endforeach; ?>
  </select>
</div>

// Now, you can load the posts when changing the option using the AJAX method
jQuery(".select-wrapper #post_type").change(function() {
  load_filtered_posts(this);
});