How to Create Custom WP Metabox

Default and custom types already have default fields that we can fill in, but what it we need custom data for these post types? In this kind of need, we can opt to create custom metaboxes which will contain custom fields for the desired post types.

Copy this abstract class on your plugin folder.

abstract class WDT_MetaBox {    

    protected $_meta_key = null;
    protected $_title = "Custom Meta Box";
    protected $_screens = array( 'post', 'page');
    protected $_context = 'normal'; //normal, side, advanced
    protected $_priority = 'default'; //high, low, default

    public function __construct($mk) {
        add_action('add_meta_boxes', array($this, 'addMetabox'));
        add_action('save_post', array($this, 'validateMetabox'));
    }   

    public function addMetabox() {
        $screens = $this->_screens;

        foreach ( $screens as $screen ) {
            add_meta_box(
                $this->_meta_key,
                __($this->_title, $this->_meta_key . '_textdomain' ),
                array($this, 'showMetabox'),
                $screen,
                $this->_context,
                $this->_priority
            );
        }
    }

    public function showMetabox($post) {
        // Add a nonce field so we can check for it later.
        wp_nonce_field($this->_meta_key . '_save_meta_box_data', $this->_meta_key . '_wpnonce');

        $this->_showForm($post);
    }

    public function validateMetabox($post_id) {
        /*
         * We need to verify this came from our screen and with proper authorization,
         * because the save_post action can be triggered at other times.
         */

        // Check if our nonce is set.
        if(!isset($_POST[$this->_meta_key . '_wpnonce'])) {
            return;
        }        

        // Verify that the nonce is valid.
        if(!wp_verify_nonce( $_POST[$this->_meta_key . '_wpnonce'], $this->_meta_key . '_save_meta_box_data')) {
            return;
        }
        
        // If this is an autosave, our form has not been submitted, so we don't want to do anything.
        if(defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE) {
            return;
        }

        // Check the user's permissions.
        if(!current_user_can('edit_post', $post_id)) {
            return;
        }

        $this->_saveMetadata($post_id, $_POST);
    }

    abstract protected function _showForm($post);

    abstract protected function _saveMetadata($post_id, $user_inputs);
}

Create a new class and extend the class from the above.

To create your own custom metabox, simply overide the Metabox class.

  • Implement the following abstract functions:
    • _showForm()
    • _saveMetadata().
  • You may also overide the class variables to fit your needs.
class PostExtraOptions extends WDT_Metabox {

    protected $_title = "Extra Options";
    protected $_screens = array( 'post');
    protected $_context = 'side'; //normal, side, advanced
    protected $_priority = 'default'; //high, low, default

    public function _showForm($post) {
    	$value = get_post_meta($post->ID, 'reference', true);
        ?>
        <div>
        	<label>Reference:</label>
        	<input type="text" name="reference" value="<?php echo $value ?>" />
        </div>
        <?php
    }

    protected function _saveMetadata($post_id, $user_inputs) {
        //OK, it's safe for us to save the data now.
        update_post_meta($post_id, 'reference', $user_inputs['reference']);
    }    	
}
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageEmail this to someone

Leave a Reply

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