Using Piklist you can easily display your registered Post Types in a Checkbox, Dropdowns (Select list) or Radio Buttons. This simple tutorial will show you how:
- Install Piklist
- Decide if you are going to build your Piklist code as a plugin or in your theme.
- With Piklist you can display fields as Metaboxes, on a Settings page or a Widget. Choose which one you want to use.
Now we can get started and write some code! We’re are going to use the WordPress function get_post_types() to get our Post Type list. This function stores data in an array, and with Piklist, parsing an array and displaying it as a Dropdown or Select List is really easy. This array stores all Post Types in an Object, and then breaks them out. You have access to fields like name and label which we will use here. We are going to assign each item in the dropdown to the name, but show the label:
piklist('field', array( 'type' => 'select' ,'field' => 'my_post_types' ,'label' => 'Choose a Type' ,'attributes' => array( 'class' => 'text' ) ,'choices' => piklist( get_post_types( array( 'public' => true ) ,'objects' ) ,array( 'name' ,'label' ) ) ));
Let’s take a look at this code:
- First we created a standard Piklist Select list.
- The only major change is the choices array. We told Piklist to use the get_post_types() function, and then passed the public parameter to Piklist. This parameter is standard to the get_post_types() function and can be found at the Codex. You can use any of the standard WordPress parameters.
- The next array tells Pikist what should be the KEY for the field, and what should be the VALUE. In this case we selected name as the KEY, and label as the VALUE to show in the list.
To make this a Checkbox, just change ‘type’ => ‘select’, to ‘type’ => ‘checkbox’.
To make this Radio Buttons, just change ‘type’ => ‘select’, to ‘type’ => ‘radio’.
Yes, it’s that easy!