Adding meta boxes to WordPress Custom Post Type

Posted on 10th February, 2015 11 Comments

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>

Comments

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]

LorenaBlairacife

17th, Sep, 20

Monty Python star meters Palin

Sir Michael Palin has opened up about his recent heart surgery saying he now feels like a “One previous owner Golf GTI” as an “Old toyota Anglia”Sir Michael Palin has opened up about his recent heart surgery saying he now seems a “One older owner Golf GTI” associated with an “Old frd Anglia,

The comedian wrote a post on his website now telling fans that his four hour operation had gone well but his biggest struggle was now trying not to do too much.

Monty Python star Sir eric, 76, Cancelled all upcoming destinations in July after admitting he needed heart surgery.

Monty Python jean Cleveland, 77, Looking for love on online dating services

he explained how he had the operation four weeks ago at St Bartholomew Hospital in London, Where surgeons experienced he actually had two leaking valves.

he explained in Wednesday’s post: “contacting the fourth week since my surgery.

“good team at Bart’s Hospital opened me up, Had a browse, Found a second valve that needed consciousness, And now associated with feeling like an old Ford Anglia I’m well on my way to feeling like a one previous owner Golf GTI.

“The operation took over four hours but I felt hardly at all pain afterwards. main problem now is trying hard not to do too much,

The excellent comedian and broadcaster continued: “My chest won’t really be ready for any gold medallions for a minimum of six weeks, and i am told the ticker, Which enlarges to deal with the extra work load from dysfunctional valves, May take a year to send back to normal size,

Michael Palin cancels book tour to have built major heart surgery

As he insisted he is longing for taking “ninety days off work doctor orders, Michael also revealed this can be his longest time off ever.

he explained: “Longest period without major work since I pointed in the biz in 1965. A chance to look into it and see what others are doing. Which at the time seems largely shouting at each other,

the nation’s treasure and travel expert said in summer that he would need major surgery to correct a leaky heart valve that was discovered during a routine health check.

Michael Palin becomes first and maybe only Monty Python star for knighthood

He said up until now: “Five rice, A routine health check pointed out a leaky mitral valve in my heart.

“Until the beginning of this year it had not affected my general level of fitness. a few weeks ago, when, I have felt my heart dealing harder and have been advised it time to have the valve repaired.

“I shall be going under the knife in September and should be back to normal, Or rather better than normal, Within three months,

Palin and the Monty Python team did sketches involving hospitals and his statement was took on his Facebook page by a [url=https://www.bestbrides.net/jump4love-reviewis-it-available-for-ukrainian-dating-online/]jump4love reviews[/url] photo of them in hospital scrubs and the words “the device that goes ping,

This refers to Monty Python film The Meaning of Life and a sketch with a fictional hospital machine that which is a device that doctors use to observe that the baby they delivering is alive.

The mitral valve is a small flap in the heart that stops blood flowing the wrong manner. troubles with it can affect how blood flows around the body.

Sir Michael was due to try a book tour this month to plug his latest offering, North Korea mag, Which follows his 2018 Channel 5 documented.

JamesVen

21st, Oct, 20

Ypgvfn uoiuha [url=https://ciamedusa.com/#]cialis buy[/url] Pkouqg vonqxi 20mg cialis tadalafil dosage

Tanqiz

24th, Nov, 20

in opposition to social media

exactly the executive order say?The order sets out to clarify the marketing and sales communications Decency Act, A US law that offers online platforms such as Facebook, Twitter and YouTube legal protection in certain issues.

Under Section 230 of regulations, Social networks are not generally held responsible for content posted by their users but can engage in “Good Samaritan stopping, Such as clearing away content that is obscene, bothering or violent.

And the draft of the executive order points out this legal immunity does not apply if a social network edits content posted by its users.

what’s more,further, it says “deceitful” stopping of posts, Including removing a post for reasons other than those described in a website’s terms of service, really offered immunity.

Republican senator Marco Rubio is among those arguing the platforms take on the role of a “founder” soon after add fact check labels to specific posts.

“But should they have now decided to exercise an editorial role like a publisher, Then they should no longer be shielded from liability and treated as publishers under the law,

The draft of the acting order also calls for:

The Federal contact Commission (FCC) To spell out what type of content blocking will be regarded deceptive, Pretextual or inconsistent with a service provider’s terms and conditionsa review of government advertising on social media sites and whether those platforms impose viewpoint based restrictionsthe re restaurant of the White House “Tech bias revealing tool” That lets citizens report unfair treatment methods by social networksHow have the social networks responded?twitter, Which is over and over named in the draft of the executive order, decreased to comment.

YouTube, Owned by search engines, Has not yet said.

In a meeting with Fox News on Wednesday, Facebook’s chief executive, symbol Zuckerberg, Said censoring a social media platform couldn’t survive the “Right response” For a government serious about censorship.

Fox said it would play its full they’re competent with Mr Zuckerberg on Thursday.

One orthodox think tank warned the executive order could have unintended consequences.

“In the long run, This subdued campaign against social media companies could have a devastating effect on the freedom of speech, Matthew Feeney, Of the Cato initiate, had to talk about.

And changing the advertising Decency Act to “Impose politics neutrality on social media companies” Could see the platforms rife with “Legal content they’d otherwise like to get rid of” Such as pornography, violent imagery and racism.

“Or they would screen content to a degree that would kill the free flow of info on social media that we’re used to today, he said.

Mr Feeney [url=https://www.bestbrides.net/dating-unlocked-understanding-east-european-women/]Charmdate.com[/url] said the draft of the accounting order was a “grime” But can be politically popular in the run up to a presidential election.

What sparked the particular row?The long term dispute between Mr Trump and social media companies flared up again on Tuesday, When two of his posts were given a fact check label by Twitter now.

he tweeted, Without providing evidence: “there’s no way (zero) That mail in ballots will be anything less than considerably fraudulent.

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]