Alex Rivera | Logout

How do I add custom fields to my custom post type in Wordpress 3?

Asked 2011-02-21T10:38:04.720
15

I created a custom post type with the register_post_type function, and now I want to add custom fields to it. These must be as user friendly and integraded in the GUI as possible.

I tried the custom field template but I dont really like it for end users. I prefer to add the new field and a new meta box with code.

Edit
Report

1 Answer

26

I found this series of tutorials were very helpful:

And if you want a straight up code sample, this code is basically the template that I use for myself: (Using Scribu's optimal script loading technique)

final class Metabox_Example {
    // These hook into to the two core actions we need to perform; creating the metabox, and saving it's contents when it is posted
    public function __construct() {
        // http://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes
        add_action( 'add_meta_boxes', array( $this, 'create_meta_box' ) );

        // http://codex.wordpress.org/Plugin_API/Action_Reference/save_post
        add_filter( 'save_post', array( $this, 'save_meta_box' ), 10, 2 );
    }

    public function create_meta_box( $post_type, $post ) {
        // http://codex.wordpress.org/Function_Reference/add_meta_box
        add_meta_box(
            'location_information_meta_box', // (string) (required) HTML 'id' attribute of the edit screen section
            __( 'Location Information', 'plugin-namespace' ), // (string) (required) Title of the edit screen section, visible to user
   
answered 2012-11-23T00:01:45.930

Your Answer