upcore/metaboxes

The meta box abstraction layer for WordPress projects. Allows you to create and manage meta boxes without extra hassle.


Keywords
wordpress, metabox, metaboxes
License
GPL-2.0

Documentation

UpCore Metaboxes

The meta box abstraction layer for WordPress projects. Allows you to create and manage meta boxes without extra hassle.

Usage

Currently this module provides \UpCore\Metabox class which you could use to create your meta box classes. This class handles meta box registration, rendering and saving processes. It adds nonce field and checks its validity during saving process.

To create your own meta box class just inherit it and implement a few methods, like this:

class MyPlugin_Metabox extends \UpCore\Metabox {

    protected function _get_nonce_field() {
        // return a name which will be used to create a nonce field
        return '_my_metabox_nonce_field_name';
    }

    protected function _get_nonce_action() {
        // return an action which will be used to create a nonce value and to verify it
        return 'my_metabox_action';
    }

    public function render( $post ) {
        // render meta box here
    }

    public function save( $post_id, $post ) {
        // nonce verified so you can save data
    }

}

After declaring your custom meta box class, you can use it like this:

add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
function myplugin_add_meta_box() {
    $metabox = new MyPlugin_Metabox();
    $metabox->register( 'metabox-id', 'Meta box title', 'post' );
}

add_action( 'save_post', 'myplugin_save_meta_box_data', 10, 2 );
function myplugin_save_meta_box_data( $post_id, $post ) {
    $metabox = new MyPlugin_Metabox();
    $metabox->save_metabox( $post_id, $post );
}

Alternative approach

This class has alternative way of usage. Instead of inhering it, you can just create an instance of the class and assign render and save callbacks to it like this:

add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
function myplugin_add_meta_box() {
    $metabox = new \UpCore\Metabox();

    $metabox->render = function( $post ) {
        // render your meta box here
    };

    $metabox->register( 'metabox-id', 'Meta box title', 'post' );
}

add_action( 'save_post', 'myplugin_save_meta_box_data', 10, 2 );
function myplugin_save_meta_box_data( $post_id, $post ) {
    $metabox = new \UpCore\Metabox();

    $metabox->save = function( $post_id, $post ) {
        // save your meta box data
    };

    $metabox->save_metabox( $post_id, $post );
}

Installation

To install this module, you just need to add it to your composer dependencies list by running following command in your terminal:

$ composer require upcore/metaboxes

How to contribute

Read this article if you want to contribute, but don't know how to do it.

License

The MIT License (MIT)