Adding meta boxes to WordPress Custom Post Type

Posted on 10th February, 2015 Leave a Comment

Lets create a folder called /meta/ and place it within our theme folder. This will hold our meta.php, meta.css and any cpt meta file.

So I’m going to presume you’ve got your custom post type created and you need to add some meta boxes which will hold specific content for the cpt.
This is how my function looks which is adding the custom post type, take note of the label:

functions.php

/*
 * ABOUT US POST TYPE
 *************************************************************/
add_action( 'init', 'about_us_post_type', 0 );
function about_us_post_type() {
 
	$labels = array(
		'name'					=> 'People',
		'singular_name'			=> 'People',
		'menu_name'		   		=> 'People',
		'parent_item_colon'   	=> 'Parent Item:',
		'all_items'		   		=> 'All People',
		'view_item'		   		=> 'View Item',
		'add_new_item'			=> 'Add New Member',
		'add_new'			 	=> 'Add New',
		'edit_item'		   		=> 'Edit Item',
		'update_item'		 	=> 'Update Item',
		'search_items'			=> 'Search Item',
		'not_found'		   		=> 'Not found',
		'not_found_in_trash'  	=> 'Not found in Trash',
	);
	$args = array(
		'label'			   		=> 'people', /* The 'label' will be used to tell the meta.php where the meta boxes should appear */
		'description'		 	=> 'Where you tell people about yourself',
		'labels'			  	=> $labels,
		'supports' 			  	=> array('title', 'editor', 'thumbnail'),
		'hierarchical'			=> false,
		'public'			  	=> true,
		'show_ui'			 	=> true,
		'show_in_menu'			=> true,
		'show_in_nav_menus'   	=> true,
		'show_in_admin_bar'   	=> true,
		'menu_position'	   		=> 5,
		'menu_icon'		   		=> ' ',
		'can_export'		  	=> true,
		'has_archive' 			=> true,
		'exclude_from_search' 	=> true,
		'publicly_queryable'  	=> true,
		'capability_type'	 	=> 'page',
	);
	 
	register_post_type( 'people', $args );
}


// WP People Categories
function build_taxonomies() {
	register_taxonomy( 'people-categories', 'people', array( 'hierarchical' => true, 'label' => 'Department', 'query_var' => true, 'rewrite' => true ) );
}
add_action( 'init', 'build_taxonomies', 0 );

meta.php

Create a blank meta.php file and add it to the your-theme/meta/ folder we just created. Open this up in your text editor.

Here we’re going to:

  1. Define the document root
  2. Link to the styles (meta.css)
  3. Add a containing metabox and give it a title
  4. Finally add a link to the php file that will contain the meta fields
<?php
 
define('ROOT',$_SERVER['DOCUMENT_ROOT']);
define('WPTRICKS_STARTER_THEME',str_replace('\\','/',dirname(__FILE__)));
define('WPTRICKS_STARTER_PATH','/' . substr(WPTRICKS_STARTER_THEME,stripos(WPTRICKS_STARTER_THEME,'wp-content')));

 
/* ABOUT META BOXES ADDED BELOW */
add_action('admin_init','wptricks_about_meta_init');
 
function wptricks_about_meta_init()
{
 
	wp_enqueue_style('wptricks_about_meta_css', WPTRICKS_STARTER_PATH . '/meta.css');
 
	foreach (array('people') as $type) /* ADD THE LABEL NAME FROM ABOVE */
	{
		/* TITLE THE CONTAINING METABOX */
		add_meta_box('wptricks_about_meta', 'Other Details Title', 'wptricks_about_meta_setup', $type, 'normal', 'high'); /* PLACEMENT: HIGH, SIDE, NORMAL, LOW */
	}
	 
	add_action('save_post','wptricks_about_meta_save');
}
 
function wptricks_about_meta_setup()
{
	global $post;
	$aboutmeta = get_post_meta($post->ID,'_wptricks_about_meta',TRUE);
	include(WPTRICKS_STARTER_THEME . '/about.php');
  
	echo '<input type="hidden" name="wptricks_about_meta_noncename" value="' . wp_create_nonce(__FILE__) . '" />';
}
 
 

finally save the meta for later

Add this to the bottom of the meta.php

 
/* SAVE ABOUT META FOR LATER */
function wptricks_about_meta_save($post_id)
{
	if (!wp_verify_nonce($_POST['wptricks_about_meta_noncename'],__FILE__)) return $post_id;
	if ($_POST['post_type'] == 'page')
	{
		if (!current_user_can('edit_page', $post_id)) return $post_id;
	} else {
		if (!current_user_can('edit_post', $post_id)) return $post_id;
	}
 
	$current_data = get_post_meta($post_id, '_wptricks_about_meta', TRUE);  /* USING THIS TO SAVE EACH META FIELD */
  
	$new_data = $_POST['_wptricks_about_meta'];
 
	wptricks_meta_clean($new_data);
	 
	if ($current_data)
	{
		if (is_null($new_data)) delete_post_meta($post_id,'_wptricks_about_meta');
		else update_post_meta($post_id,'_wptricks_about_meta',$new_data);
	}
	elseif (!is_null($new_data))
	{
		add_post_meta($post_id,'_wptricks_about_meta',$new_data,TRUE);
	}
 
	return $post_id;
}
 
 

Add our metaboxes

next we’ll create a file with our specific metaboxes added, this is the section that will be viewable from the admin screen of WordPress.

Create a new file called something relative to the post type your adding it too.

people.php

I want to create four fields name, email, job title, pa email address.
Add this:

<div class="wptricks_meta_control">
	<!-- AGAIN... USING DASH ICONS -->
 	<div class="float-three">
         <label><div class="dashicons dashicons-welcome-learn-more"></div> Position Held</label>
        <p>
            <input type="text" name="_wptricks_about_meta[position]" value="<?php if(!empty($aboutmeta['position'])) echo $aboutmeta['position']; ?>"/>
            <span>Enter the current position held within the company. </span>
        </p>
     </div>
     <div class="float-three">
        <label><div class="dashicons dashicons-email-alt"></div> Contact Email Address</label>
     
        <p>
            <input type="text" name="_wptricks_about_meta[email]" value="<?php if(!empty($aboutmeta['email'])) echo $aboutmeta['email']; ?>"/>
            <span>Enter your email address here.</span>
        </p>
    </div>
     <div class="float-three">
        <label><div class="dashicons dashicons-email-alt"></div> PA Email Address</label>
     
        <p>
            <input type="text" name="_wptricks_about_meta[paemail]" value="<?php if(!empty($aboutmeta['paemail'])) echo $aboutmeta['paemail']; ?>"/>
            <span>Enter the PA's email address here.</span>
        </p>
 	</div>
</div>

meta.css

Create this file and add it to your meta folder. We’re simply going to add the styles to display our input fields above.

/*  I'M ADDING AN ICON FROM DASHICONS THE DEFAULT ICON FONT INCLUDED IN WORDPRESS - ABOUT US ICON */
#adminmenu .menu-icon-people div.wp-menu-image:before {
			content: "\f307";
}
	

.wptricks_meta_control:before,
.wptricks_meta_control:after {
	content: "";
	display: table;
}
.wptricks_meta_control:after {
	clear: both;
}
.wptricks_meta_control .description {
	display: none;
}
.wptricks_meta_control P {
	margin: 0;
}
.wptricks_meta_control label {
	display: block;
	font-weight: bold;
	margin: 6px;
	margin-bottom: 0;
	margin-top: 12px;
}
 
.wptricks_meta_control label span {
	display: inline;
	font-weight: normal;
}
 
.wptricks_meta_control span {
	text-transform: capitalize;
	color: #999;
	display: block;
}
 
.wptricks_meta_control hr {
	border-bottom: 1px dashed #aaa;
    border-top: none;
    clear: both;
    height: 20px;
}
 
.wptricks_meta_control textarea,
.wptricks_meta_control input[type='text'] {
	margin-bottom: 3px;
	width: 99%;
}
 
.wptricks_meta_control h4 {
	color: #999;
	font-size: 1em;
	margin: 15px 6px;
	text-transform: uppercase;
}
.full-width {
	clear: both;
	width: 100%;
}
.float-two {
	float: left;
	width: 48.25%;
}
.float-two:nth-of-type(2n+1) {
	margin-right: 1.5%;
}
.float-three {
	float: left;
	width: 31.6%;
}
.float-three {
	margin-right: 2.5%;
}
.float-three:nth-of-type(3) {
	margin-right: 0;
}

Finally you’ll want to display this new info in our theme, so in the page template of your choice you can use these calls.

/* We output the meta fields using */  <?php echo $my_about_meta['email']; ?> /* CHANGE THE EMAIL TO THE NAME OF THE FIELD CREATED */

<?php // Check we have the content
	$my_about_meta = get_post_meta($post->ID,'_wptricks_about_meta',TRUE); ?>
	<h3 class="people"><?php // Output the name
			 echo the_title(); ?></h3>
			 
	<p><?php // Output Position
			 echo $my_about_meta['position']; ?></p>
			 
	<ul class="email-links">				 
	<?php if(!empty ($my_about_meta['email'])) {?>
	  <li><a href="javascript:void();" onClick="location.href='mailto:<?php echo $my_about_meta['email']; ?>'"><img src="<?php bloginfo('template_directory'); ?>/images/envelope.jpg" border="0">EMAIL</a></li>
	<?php }; ?>
	<?php if(!empty ($my_about_meta['paemail'])) {?>
	  <li><a href="javascript:void();" onClick="location.href='mailto:<?php echo $my_about_meta['paemail']; ?>'"><img src="<?php bloginfo('template_directory'); ?>/images/envelope.jpg" border="0">PA</a></li>
   <?php }; ?>
   </ul>

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]