Naveed Anjum
+92 313 514 6669

Create Metabox in WordPress

Following is the code to create Meta Box for Custom Post Type Services and in WordPress.

/**
 Metabox for the Services custom post type
 *
 @package     Naveed
 @link        http://naveedanjum.info
 Author:      Naveed
 License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 *
 */ 
 function naveed_service_metabox()
 {
 	new Naveed_Projects_CLS();
 }
 if (is_admin()) {
 	add_action('load-post.php', 'naveed_service_metabox');
 	add_action('load-post-new.php', 'naveed_service_metabox');
 }
 class Naveed_Projects_CLS{
 	public function __construct()
 	{
 		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
 		add_action( 'save_post', array( $this, 'save' ) );
 	}
 	public function add_meta_box( $post_type ) {
 		global $post;
 		add_meta_box(
 			'naveed_services_metabox', 
 			__( 'Service Tagline', 'naveed' ), 
 			array( $this, 'render_meta_box_content' ), 
 			'services', 
 			'advanced', 
 			'high'
 		);
 	}
 	public function save( $post_id ) {
 		if ( ! isset( $_POST['naveed_service_nonce'] ) )
 			return $post_id;

 		$nonce = $_POST['naveed_service_nonce'];

 		if ( ! wp_verify_nonce( $nonce, 'naveed_service' ) )
 			return $post_id;

 		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
 			return $post_id;

 		if ( 'services' == $_POST['post_type'] ) {

 			if ( ! current_user_can( 'edit_page', $post_id ) )
 				return $post_id;

 		} else {

 			if ( ! current_user_can( 'edit_post', $post_id ) )
 				return $post_id;
 		}
 		$service_tagline = isset( $_POST['naveed_service_tagline'] ) ? esc_html($_POST['naveed_service_tagline']) : false;   
 		update_post_meta( $post_id, 'naveed-service-tagline', $service_tagline );
 	}
 	public function render_meta_box_content( $post ) {
 		wp_nonce_field( 'naveed_service', 'naveed_service_nonce' );
 		$service_tagline = get_post_meta( $post->ID, 'naveed-service-tagline', true );

 		echo '<p><em>'._e("Enter Tagline Here.", "naveed").'</em></p>';
 		echo '<p><input type="text"class="widefat" id="naveed_service_tagline" name="naveed_service_tagline"value="'.esc_html($service_tagline).'"></p>';

 	}
 }
Previous Post Next Post

Comments

Leave a Reply

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