Last active
August 29, 2015 14:00
-
-
Save carmichaelize/11061870 to your computer and use it in GitHub Desktop.
Wordpress Metabox Wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class custom_metabox { | |
//Custom metabox key | |
public $key = 'meta_box_key'; | |
//Custom metabox options | |
public $options = array( | |
'post_types' => get_post_types(), | |
'title' => 'Meta Box Title', | |
'context' => 'side', //normal, advanced, side | |
'priority' => 'low', //default, core, high, low | |
'description' => '' | |
); | |
public function custom_meta_add(){ | |
foreach( $this->options->post_types as $post_type ){ | |
//$key, $title, $callback, $post_type, $context, $priority, $callback_args | |
add_meta_box( | |
$this->key, | |
esc_html__( $this->options->title ), | |
array(&$this, 'custom_meta_render' ), | |
$post_type, | |
$this->options->context, | |
$this->options->priority, | |
$callback_args = null | |
); | |
} | |
} | |
public function custom_meta_render( $object, $box ){ | |
wp_nonce_field( basename( __FILE__ ), $this->key.'_nonce' ); | |
$data = get_post_meta( $object->ID, $this->key, true ); | |
//Render metabox HTML | |
//<input type="text" class="widefat" value="" /> | |
} | |
public function custom_meta_save( $post_id, $post = false ){ | |
//Verify nonce | |
if ( !isset( $_POST[$this->key.'_nonce'] ) || !wp_verify_nonce( $_POST[$this->key.'_nonce'], basename( __FILE__ ) ) ){ | |
return $post_id; | |
} | |
//Check posted data | |
$new_meta_value = ( isset( $_POST[$this->key] ) ? $_POST[$this->key] : '' ); | |
//Get previously saved data | |
$meta_value = get_post_meta( $post_id, $this->key, true ); | |
//Add, update and delete data | |
if( $new_meta_value && '' == $meta_value ){ | |
add_post_meta( $post_id, $this->key, $new_meta_value, true ); | |
} elseif ( $new_meta_value && $new_meta_value != $meta_value ){ | |
update_post_meta( $post_id, $key, $new_meta_value ); | |
} elseif ( '' == $new_meta_value && $meta_value ){ | |
delete_post_meta( $post_id, $key, $meta_value ); | |
} | |
} | |
public function custom_meta_setup() { | |
//Add metaox | |
add_action( 'add_meta_boxes', array( &$this, 'custom_meta_add' ) ); | |
//Save metabox | |
add_action( 'save_post', array( &$this, 'custom_meta_save' ) ); | |
} | |
public function __construct( $params = array() ){ | |
//Create options object | |
$this->options = (object)$this->options; | |
//Add custom metabox | |
add_action( 'init', array( &$this, 'custom_meta_setup' ) ); | |
} | |
} | |
new custom_metabox(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment