Tutorial: Display Taxonomies as a Dropdown or Radio Buttons

Using Piklist you can easily display your Taxonomies as a Dropdown (Select list) or as Radio Buttons.  This simple tutorial will show you how:

  1. Install Piklist
  2. Decide if you are going to build your Piklist code as a plugin or in your theme.
  3. 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_terms(), to get our taxonomy values.  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.  As you can see from the WordPress Codex page, this array stores all users in an Object, and then breaks them out.  You have access to fields like term_id, name, parent etc.  We are going to assign each item in the dropdown to the term_id, but show the name. This is added to the Piklist parameter choices:

piklist('field', array(
    'type' => 'select'
    ,'scope' => 'taxonomy'
    ,'field' => 'piklist_demo_type'
    ,'label' => 'Demo Types'
    ,'description' => 'Terms will appear when they are added to this taxonomy.'
    ,'choices' => piklist(
      get_terms('piklist_demo_type', array(
        'hide_empty' => false
      ))
      ,array(
        'term_id'
        ,'name'
      )
    )
  ));

Let’s take a look at this code:

    • First we created a standard Piklist Select list.
    • Notice we set the scope here. In most cases Piklist will automatically determine the scope. But when using taxonomies you will need to set ‘scope’ => ‘taxonomy’
    • The choices array gets pulled in dynamically. We told Piklist to use the get_terms() function, and told it to get the pikist_demo_type taxonomy values.  We could have easily told it to pull in the standard category taxonomy, and assign those values to any field name we wanted. It could be category or in this case piklist_demo_type.  We also passed the hide_empty parameter to Piklist.  This parameter is standard to the get_terms() function and can be found at the Codex.
    • The next array tells Pikist what should be the KEY for the field, and what should be the VALUE.  In this case we selected term_id as the KEY, and name as the VALUE to show in the list.

Radio Buttons:

To make this Radio Buttons, just change ‘type’ => ‘select’, to ‘type’ => ‘radio’.

Yes, it’s that easy!