AppThemes Docs

Creating Custom Post Meta Boxes

Across all our themes, we use a lot of post meta boxes to give site owners the ability to easily edit data attached to posts, listings, and other items in their admin interface. We do it so much that we’ve created a really simple API to make creating post meta boxes incredibly fast and simple.

All the magic is held in a utility class in our framework called APP_Meta_Box. It is automatically loaded on most admin pages when you’re running one of our themes.

class My_Meta_Box extends APP_Meta_Box {
	public function __construct() {
		parent::__construct( 
                    'meta-box-identifier', 
                    'Meta Box Title', 
                    'post-type', 
                    'priority' 
                );
	}
	public function form_fields() {
		return array();
	}
	function before_save( $data, $post_id ) {
		return $data;
	}
}

Using the utility class is pretty simple. You need a constructor that calls the parent class with the arguments that direct where the meta box will show up. You can then use the `form_fields()` method to define the form fields that will be shown. Our utility class will automatically handle saving.

Example: Adding Media Contact Information

Let’s say that you wanted to add a field that let you store the media contact representative users should contact in reference to a post. You could use a meta box to prompt the author for that information.

class My_Media_Contact_Box extends APP_Meta_Box {
	public function __construct() {
		parent::__construct( 
                    'media-contact-info', 
                    'Media Contact', 
                    'post', 
                    'normal' 
                );
	}
	public function form_fields() {
		return array(
			array(
				'title' => __( 'Contact Name' ),
				'type' => 'text',
				'name' => 'media_contact_name',
			),
			array(
				'title' => __( 'Contact Email' ),
				'type' => 'text',
				'name' => 'media_contact_email',
			),
		);
	}
}

Its that simple. You can go into /framework/admin/class-meta-box.php to poke around more and see all the other awesome features of our meta box class.

Like this tutorial? Subscribe and get the latest tutorials delivered straight to your inbox or feed reader.

Your rating: none
Rating: 5 - 2 votes