Genuine Juice

Sip on our thoughts about the age of digital engagement.

Adding Custom Field GUI to Custom Post Types in WordPress 3.0

While WordPress 3.0 comes with a slew of front-facing features that bloggers new to the platform will be excited to play with, the really interesting improvements for 3.0 are behind the scenes: write panels for custom post types, GUI for hierarchical taxonomies, and a fully dynamic menu system that allows end users to drag-and-drop practically anything into a custom menu.

Developers who’ve been following Trac and digging into the WP core have been quietly taking advantage of WP’s support for custom post types for awhile, but until now, there was no easy way to generate new write panels with simple function calls, let alone generate GUI for custom fields associated with those post types. What WP lacked was support for the end user: that is, GUI in the Dashboard. And what makes WP so wildly popular among bloggers is its slick, user-friendly front-end.

Custom Fields with a GUI

During the 2.6 to 2.9 era, the easiest (read: hackiest) solution for adding GUI to custom fields and generating write panels on the fly was through plugins like Flutter (or later on, its fork, Magic Fields). We also used the plugin Pods to hack together CMS-like relationships between posts, but handing over a Pods’d project to a non-technical client is a recipe for disaster.

But now, WordPress has arrived as a CMS. Even in beta, WordPress renders plugins like Flutter and Pods obsolete. Creating a custom post type and generating a write panel for it in the Dashboard is as easy as adding a new function to your functions.php. Suppose you wanted to add a “Kittens” type of post with two custom taxonomies: a hierarchical “Breeds” taxonomy, which functions in the same way that Categories do for posts, and a non-hierarchical “Meta Keywords” taxonomy for use with SEO meta keywords, which functions in the same way that Tags do.

// create post type: kittens

if ( ! function_exists( 'post_type_kittens' ) ) :

function post_type_kittens() {

	register_post_type(
		'kittens',
		array(
			'label' => __('Kittens'),
			'description' => __('Create a kitten.'),
			'public' => true,
			'show_ui' => true,
			'register_meta_box_cb' =>
                        'init_metaboxes_kittens',
			'supports' => array (
				'title',
				'editor',
				'thumbnail',
				'excerpt',
				'custom-fields'
			)
		)
	);

register_taxonomy( 'breeds', 'kitten-breeds',
array ('hierarchical' => true, 'label' => __('Breeds')));

register_taxonomy( 'kittenmeta', 'kitten-meta',
array ('hierarchical' => false, 'label' => __('Meta Keywords'),
'query_var' => 'kittenmeta'));

}

endif;

add_action('init', 'post_type_kittens');

New Write Panels

Look straightforward? It sure is. A couple of interesting bits in this chunk of code:

  • The “supports” array allows you to define what meta boxes you want to appear in the edit screen for the Kittens-type post; in my case, I’ve specified the title field, the TinyMCE editor, the new post thumbnail from 2.9, the excerpt field, and custom fields.
  • I’ve included a call to the function (“init_metaboxes_kittens”) that will initialize my custom meta boxes, which I’ll use to add GUI to the custom fields associated with my Kittens posts. More on that later.
  • Finally, I’ve used register_taxonomy to add the hierarchical and non-hierarchical taxonomies.

Once I add this stuff to functions.php, I can copy the single.php template and then create a template called “single-kittens.php” to handle kittens posts exactly as I would handle WP’s default post type in the single.php template. Don’t forget to reset your permalinks so you can access the new post type: http://www.yourdomain.com/kittens/name-of-kitten/ would work, as would http://www.yourdomain.com/breeds/name-of-kitten/.

Adding custom meta boxes to the Kittens post type is a little more complicated, but once you have the method in place, you can tack on custom fields with GUI to your heart’s content. Thankfully, register_post_type allows us to hook in add_meta_box functions and thereby save custom meta fields within a custom post type’s edit screen.

Much of the code below comes from Charles Clarkson’s Add Dynamic Meta Boxes plugin. The original plugin works with the built-in Posts and Pages post types in the WordPress core. For our exercise, I’ve integrated his plugin with the register_post_type hook, so that you can add meta boxes directly in your functions file.

You can download the full script here: add_meta_boxes.txt

Things to pay attention to:

The $sp_boxes array is where we define each set of custom fields for the Kitten post type. Each array represents a custom field (so for example, _kitten_color is a custom field that will appear in a group with _kitten_age and _kitten_favorite_website in the “About the Kitten” group within the Kitten post type edit screen.) By default, each custom field is displayed as a single-line text field. Alternatively, you can display the field as a textarea field by specifying “textarea” as the final value.

$sp_boxes = array (
	'About the Kitten' => array (
		array( '_kitten_color', 'Color', 'Color of kitten?'),
		array( '_kitten_age', 'Age', 'How old is it?'),
		array( '_kitten_favorite_website', 'Favorite Website', 'Favorite website?')
	),
	'Litter Boxes' => array (
		array( '_litter_description', 'Description', 'Describe litter box.', 'textarea' ),
		array( '_litter_features', 'Features', 'Features of litter box?', 'textarea' ),
	)
);

What if you want to add new custom field types? Like, say, a checkbox or dropdown selection? Creating new input field types for your meta boxes is a matter of adding the new input to the case statement in the attached script, and writing a new function to handle the meta box. Here is the case statement (which is included in the demo text file):

// this switch statement specifies different types of meta boxes
// you can add more types if you add a case and a corresponding function to handle it
if ( ! function_exists( 'field_html' ) ) :
function field_html ( $args ) {
	switch ( $args[3] ) {
		case 'textarea':
			return text_area( $args );
		case 'checkbox':
			return sp_checkbox( $args );
		default:
			return text_field( $args );
	}
}
endif;

If we added a case for a checkbox or select dropdown, we’d have to create a corresponding function to handle it. In this way, you can write a function to handle any type of input field, and the best part is that you have access to all the functions you normally would within functions.php. This means, for example, you can query the database to populate a dropdown with posts, creating custom field-based relationships between one custom post type and another. And that’s just the beginning.

So, what do you plan to do when WP 3.0 comes out? With 35% left in Trac as of April 8, it won’t be long…

Comments

  1. Sep 18 2011 Justin House says

    This is completely awesome! This is the most extensive post I’ve found about integrating custom post types and custom fields. Thank you. I’ve been using Magic Fields for awhile, quite successfully, however, I want to go pure WordPress custom post types and custom fields. My only issue is creating a simple image upload, like Magic Fields offers, ’cause they nailed it and made it simple and self-explanatory for end users! I understand WordPress has a Featured Image upload, but it’s a little trivial for people; I want to keep it as straight forward as possible. Any suggestions?

    Thanks.

  2. Sep 28 2011 Genuine Interactive says

    Hi Justin, our advice is that you create a new GUI type called “image” for example, and define that custom meta as having a link that triggers the Media Library. You’ll need to write some script to pass the URL of the uploaded image back to the input field, and then you’ll be able to take advantage of the Media Library.

  3. Apr 10 2013 oliver says

    Hi!!, look awesome your tutorial, but I had a problem, i wanted to download the txt and it redirects me to a 404 page. If you could upload again the script would be grat!!. Thank you

  4. Apr 10 2013 Genuine Interactive says

    Hi Oliver! Unfortunately since this post is several years old, the script is no longer available on our servers. We’re always working with WP, however, so keep a look out for posts like these in the future.

  5. Jul 25 2013 best seo news says

    I almost never leave a response, however i did a few searching and wound up here Adding Custom Field GUI to Custom Post Types in WordPress 3.
    0 » Genuine » The Digital Agency for the Age of
    Engagement. And I actually do have 2 questions for you if it’s allright. Is it just me or does it look like some of these comments appear as if they are left by brain dead folks? :-P And, if you are posting on additional sites, I would like to follow everything fresh you have to post. Could you make a list of the complete urls of all your social pages like your Facebook page, twitter feed, or linkedin profile?

  6. Jan 14 2014 how to make money says

    I’ve been exploring on line greater than Three hours nowadays, but I never found every useful article such as you. It is really beautiful price sufficient for me personally. In my opinion, when most webmasters as well as blog writers produced superior information just like you do, websites would have been a great deal more handy than previously.

  7. Apr 7 2014 health says

    I was suggested this website through my cousin.
    I am not certain whether this publish is written through him as
    no one else realize such distinctive approximately my difficulty.
    You are incredible! Thank you!

    Also visit my webpage: health

Have Something to Say?

Your email address will not be published. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>