FrugalWebGuy is Merging with Michael Mann Web Design under the new Title of I Do Web Work

Build Array of Post Types

Video Available (Signup to Access - Members Only)

Theme Building Training

There may come a time where you will desired to build array of posts types. I needed such a thing to create checkboxes for the hide title feature of My Simple theme. So let's take a look at how this array is pulled together, starting with the code.

Build Array of Post Types

$post_types = get_post_types( array(
 "public" => true,

foreach( $post_types as $post_type ) {
 $post_names[$post_type->name] = $post_type->labels->menu_name;

The first line uses the get_post_types() function, which accepts three items: arguments, which in our case are post types marked as public, an output, objects in our case to give us an array of elements for each of the post types, and the operator, since we want all public post types we choose "and".

Choosing the output of objects allows us to pick an array value combination, the name for the key and the menu_name label for the value. Choosing to go this route will end up allows us to build an array like the following, , thanks to the foreach loop cycling through all of the returned post types:

// List Post Types
$post_names = array(
 "post" => "Post",
 "page" => "Page",
 "media" => "Media"

This setup will allow us to have both a key and a value, so we can end up with the following for those checkboxes in the theme options panel, under both the Allow Hide Title option and Allow Sidebar Placement like this:

<div class="post-type-option">
<input id="my-simple-theme-post_types-post" class="checkbox of-input" name="my-simple-theme[post_types][post]" type="checkbox" />
<label for="my-simple-theme-post_types-post">Posts</label>

This is just to fancy it up a bit, but an array of post types can do so much more.