Easy WordPress Metaboxes with MetaBox.io

Posted on 18th January, 2016 Leave a Comment

I’ve been using this plugin for a while now and thought I should share what I’ve come to learn is an absolute treat of a plugin!

I don’t often use plugins, let alone endorse them but for me metabox.io is an essential tool when creating complex customer WordPress sites, it’s really easy to use and hopefully once you’ve finished this post, you will see why.

Below is a copy of the demo.php file hosted on GitHub, which contains all the default metabox variations required to use the plugin. It’s a ton of code so have hidden it to save you some scrolling.

You can toggle the view with the button below!

Once you’ve installed the plugin start adding your metaboxes

Creating a file meta-boxes.php and add it to the root theme folder, then include the file through the functions.php.
At the top of your functions.php add this to include the metaboxes.php.

/*
 * META BOXES INCLUDES
 *************************************************************/
include('meta-boxes.php');

meta-boxes.php

Now let’s add some metaboxes…

If you look through the demo.php file you will find

add_filter()

and the

function()

. You need to add your own prefix to both of these. See below.

<?php
/**
 * Registering meta boxes
 *
 * All the definitions of meta boxes are listed below with comments.
 * Please read them CAREFULLY.
 *
 * You also should read the changelog to know what has been changed before updating.
 *
 * For more information, please visit:
 * @link http://metabox.io/docs/registering-meta-boxes/
 */


add_filter( 'rwmb_meta_boxes', 'wptricks_register_meta_boxes' );

/**
 * Register meta boxes
 *
 * Remember to change "your_prefix" to actual prefix in your project
 *
 * @param array $page_meta_boxes List of meta boxes
 *
 * @return array
 */
function wptricks_register_meta_boxes( $page_meta_boxes )
{

Then create a prefix for your meta keys, I recommend prepending with an underscore to keep the keys hidden.

The reason for using a prefix can prevent it from conflicting with other scripts that also use custom fields!

/**
	 * prefix of meta keys (optional)
	 * Use underscore (_) at the beginning to make keys hidden
	 * Alt.: You also can make prefix empty to disable it
	 */
	// Better has an underscore as last sign to give clarity to the id that this will attach to
	$prefix = '_wpt_';

You will use this as the prefix for all your meta key id’s when you need to call them in your template files, this will make more sense as you follow this tutorial. (I’ll provide you with an working example of this once we’ve added some metaboxes to our page).

Let’s look at the attributes used by the metabox.io plugin to gain an understanding of what they do.

Meta Box Attributes

Name Description
id Meta box ID. Optional. If it’s absent, it will be generated from title using sanitize_title function.
title Meta box title. Required.
post_types Custom post types which the meta box is for. There can be array of multiple custom post types or a string for single post type. Optional. Default: post. This parameter is used instead of pages since version 4.4.1 (and fallback to pages for previous versions). See change log.
context Part of the page where the meta box is displayed (normal, advanced or side). Optional. Default: normal.
priority Priority within the context where the box is displayed (high or low). Optional. Default: high.

Adding a metabox to a page

[1.1] A Simple Text Example

I’ll start with something simple like a custom meta title (These are used by search engines to describe what our page/post is about to potential searchers), but all I’m doing is adding a text field which can be used for any other purpose where extra text is required.

Below the prefix we defined above, add our first metabox.

Pay special attention to our id, this will be used to call our meta field prefixed with our _wpt_ that we added to our $prefix at the top of the post.

	/*
	 * PAGE TITLE/META ATTRIBUTE
	 **/
	 $page_meta_boxes[] = array(	
	
		// Meta box title - Will appear at the drag and drop handle bar. Required.
		'title'  => __( 'Meta Title.<small><span style="float: right;">Click to Expand / Collapse</span></small> ', 'wptricks' ),

		// Post types, accept custom post types as well - DEFAULT is 'post'. Can be array (multiple post types) or string (1 post type). Optional.
		'post_types' => array( 'page' ),

		// Where the meta box appear: normal (default), advanced, side. Optional.
		'context'    => 'normal',

		// Order of meta box: high (default), low. Optional.
		'priority'   => 'high',
		
		// Auto save: true, false (default). Optional.
		'autosave'   => true,

		'fields' => array(
	 	// FEATURE HEADER
			array(
				// Field name - Will be used as label
				'name'  => __( 'Page Meta Title', 'wptricks' ),
				// Field ID, i.e. the meta key
				'id'    => "{$prefix}metatitle",
				// Field description (optional)
				// This is displayed above 
				'desc'  => __( 'Add the title which is displayed within search engine results (google, bing, yahoo, etc... ).', 'wptricks' ),
				'type'  => 'text',
				'class' => 'full-width'
			),
		)
	 );
	// SEPARATE METABOXES WILL BE DEFINED BELOW THIS METABOX...
	
	// KEEP THIS LINE AT THE BOTTOM OF THE META.PHP FILE
	return $page_meta_boxes;
}

The above will appear within our Admin New/Edit Pages section of WordPress like the image below (I’ve included a title to the box already).

Capture

Once this is saved you’ll need to use this on the front-end. I like to use a condition to check for the existence of any content.

[1.2] Displaying the meta content

To display these meta fields, we’ll follow this format…

rwmb_meta('{$prefix}some_meta_id')

Notice the {$prefix} – This will be replaced with the $prefix that was created earlier. If you’re copy pasting my code without changing it, then the {$prefix} will become _wpt_.

The some_meta_id part will be replaced with the id that is assigned to the meta field that we want to output.


Lets do the actual output of the 1.1 metabox creation

As my example is going to be used for a META tag, this will go in the header.php. But this can be output into any part of your theme…

		<title><?php  // CREATE A VARIABLE TO HOLD OUR META TITLE
				$metatitle = rwmb_meta('_wpt_metatitle');
				// CHECK IF THE META TITLE HAS ANY CONTENT
					if(!empty($metatitle)){
						// USE STRIP_TAGS BECAUSE THIS IS A META TITLE!
						echo strip_tags($metatitle); 
					}  else {
						// IF METATITLE DOESN'T EXIST USE THE DEFAULT TITLE AND BLOG NAME
						wp_title(''); if(wp_title('', false)) { 
					echo ' | '; } bloginfo('name'); echo ' | '; the_title();} 
		?></title>

Like most of the metaboxes this is simple to display. If we’re using the clone attribute or using this with images (like the plupload)? Then we’ll need to use a foreach() loop to display them.


[2.1] Image Uploads and a foreach loop

Let’s create a metabox that allows us to upload our images and then display these in our pages.

$page_meta_boxes[] = array(
		// Meta box title - Will appear at the drag and drop handle bar. Required.
		'title'  => __( 'Image Plupload  <small style="display: block; clear: both;">This is where we upload our images.<span style="float: right;">Click to Expand / Collapse</span></small> ', 'wptricks' ),

		// Post types, accept custom post types as well - DEFAULT is 'post'. Can be array (multiple post types) or string (1 post type). Optional.
		'post_types' => array( 'page' ),
		// Order of meta box: high (default), low. Optional.
		'priority'   => 'low',
		// Auto save: true, false (default). Optional.
		'autosave'   => true,
		'fields' => array(// PLUPLOAD IMAGE UPLOAD (WP 3.3+)
			array(
				'name'             => __( 'Image Upload', 'wptricks' ),
				'id'               => "{$prefix}feature1_plupload",
				'type'             => 'plupload_image',
				// Field description (optional)
				'desc'  => __( 'Upload a square/circluar image image only! This automatically becomes circular and has a grey border applied.', 'wptricks' ),
				'max_file_uploads' => 1,
			),
		)
	);

This will be displayed something like this in our page/post admin screen.
Capture

[2.2] Displaying the meta plupload image

Options for the image content are:

    'name'        => 'logo-150x80.png'
    'path'        => '/home/wptricks/public_html/wp-content/uploads/logo-150x80.png'
    'url'         => 'http://example.com/wp-content/uploads/logo-150x80.png'
    'width'       => 150
    'height'      => 80
    'full_url'    => 'http://example.com/wp-content/uploads/logo.png'
    'title'       => 'Logo'
    'caption'     => 'Logo caption'
    'description' => 'Used in the header'
    'alt'         => 'Logo ALT text'

I’ll just pull the image URL straight into an image tag for this example by using the url – {$image['url']} and the title is being pulled by using the title – {$image['title']}.

<?php // CREATE A VARIABLE THAT CONTAINS THE IMAGE
		// NOTICE! - THE 'SIZE=' THIS HAS BEEN DEFINED IN THE USUAL WAY IN OUR FUNCTIONS.PHP
		// WITHOUT THIS YOU'LL GET THE INFO FOR THE DEFAULT THUMBNAIL SIZE (150 X 80)
		$img = rwmb_meta( '_wpt_feature1_plupload', 'type=plupload_image&size=round-feature-image' );

		foreach ( $img as $image )
		{
			echo "<img src='" . "{$image['url']}" . "' alt='" . "{$image['title']}" . "'>";
		}
	 ?>

EXTRA
If you would like to grab meta content that has been added anywhere else in your site. You can do this by using the post_id from the page that you’ve added the meta content too and add this to the meta call!

EXAMPLE
Using the image example above, in this extra snippet I’m grabbing the post id via post title to pull only images which have been added added to the ‘Home Page’ – ‘_wpt_feature1_plupload’.

<?php 
	// GRAB THE POST ID BY POST/PAGE TITLE ($post_title, OBJECT, $post-type)
	$my_post = get_page_by_title( 'Home Page', OBJECT, 'page' ); 
	$postid = $my_post->ID;
	
	// NOW CREATE A VARIABLE THAT CONTAINS THE IMAGE AMD INCLUDE THE $POSTID TO THE CALL
		$img = rwmb_meta( '_wpt_feature1_plupload', 'type=plupload_image&size=round-feature-image', $postid );

		foreach ( $img as $image )
		{
			echo "<img src='" . "{$image['url']}" . "' alt='" . "{$image['title']}" . "'>";
		}
	 ?>

[3.1] Using Checkboxes

Checkboxes can be used in a number of ways from content to applying styles…

I’m going to show you how you can use a checkbox to add a class to an tag within your page. You could use this to control the display of an item or even align a sidebar to the left or right of the page. Just add the relevent styles to your CSS for the class.

First you want to add a checkbox to the meta.php

// CHECKBOX
array(
	'name' => __( '<b>Hide content on mobiles</b>', 'wptricks' ),
	'id'   => "{$prefix}hide-checkbox",
	'type' => 'checkbox',
	// Value can be 0 or 1
	'std'  => 0,
),

[3.2] Using the value to display something…

Then I’m simply going to store the meta field into a variable and check against it’s content to add a class to a div.

<?php
	$checked = rwmb_meta('_wpt_hide-checkbox');
	if($checked = 1) {
		$checked = 'hidden';
	} else {
		$checked = '';
	}
?>
<div class="<?php echo $checked; ?>">Should I show this on mobiles?</div>

All the documentation on how to use metabox.io can be found here https://metabox.io/docs/

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]