Advertisement

A Guide to WordPress Custom Post Types: Creation, Display and Meta Boxes

by

WordPress is built for customization. It was created in such a way that each and every section is customizable. In this tutorial we will be exploring one of the most powerful features of WordPress known as Custom Post Types and how WordPress reached a new height with the advent of this wonderful feature.


What Actually Are Custom Post Types?

Suppose you want your blog to have a separate section for Movie Reviews. By using Custom Post Types you can create a new type of item like Posts and Pages, which will contain a different set of data. It will have a new administration menu, dedicated editing pages, custom taxonomies and many more utilities required for full fledged publishing.

Custom Post Types are a new set of administrative options appearing along with the default post types such as Posts, Pages, Attachments etc. A Custom Post Type can store any type of information. It has a dedicated editor, media uploader and uses the existing WordPress table structure for ease in data management. The main advantage of creating custom post types using the WordPress API is that it equips itself well with existing themes and templates. Custom Post Types are also SEO friendly because of their nifty permalinks.


Why Use Custom Post Types?

Custom Post Types help us to keep different types of posts in different buckets. It separates our regular posts from others. Simple enough!


Let's Create a Custom Post Type Plugin

Here we shall create a custom post type plugin which will display favorite movie reviews. Lets get started.

Step 1: Create WordPress Plugin Directory

Open your WordPress Plugin directory and create a new directory called Movie-Reviews.

Step 2: Create PHP File

Open the directory and create a PHP file named Movie-Reviews.php.

Step 3: Add Header

Open the file and add the appropriate header at the top.

<?php
/*
Plugin Name: Movie Reviews
Plugin URI: http://wp.tutsplus.com/
Description: Declares a plugin that will create a custom post type displaying movie reviews.
Version: 1.0
Author: Soumitra Chakraborty
Author URI: http://wp.tutsplus.com/
License: GPLv2
*/
?>

Step 4: Register Custom Function

Before the closing of the PHP command, type the following line of code to execute the custom function named create_movie_review during the initialization phase every time a page is generated.

add_action( 'init', 'create_movie_review' );

Step 5: Function Implementation

Provide an implementation of the create_movie_review function.

function create_movie_review() {
	register_post_type( 'movie_reviews',
		array(
			'labels' => array(
				'name' => 'Movie Reviews',
				'singular_name' => 'Movie Review',
				'add_new' => 'Add New',
				'add_new_item' => 'Add New Movie Review',
				'edit' => 'Edit',
				'edit_item' => 'Edit Movie Review',
				'new_item' => 'New Movie Review',
				'view' => 'View',
				'view_item' => 'View Movie Review',
				'search_items' => 'Search Movie Reviews',
				'not_found' => 'No Movie Reviews found',
				'not_found_in_trash' => 'No Movie Reviews found in Trash',
				'parent' => 'Parent Movie Review'
			),

			'public' => true,
			'menu_position' => 15,
			'supports' => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ),
			'taxonomies' => array( '' ),
			'menu_icon' => plugins_url( 'images/image.png', __FILE__ ),
			'has_archive' => true
		)
	);
}

The register_post_type function does most of the work for us. As soon as it is called it prepares the WordPress environment for a new custom post type including the different sections in the admin. This function takes two arguments: the first one is an unique name of the custom post type and the second one an array demonstrating the properties of the new custom post type. Here it's another array containing the different labels, which indicates the text strings to be displayed in the different sections of the custom post type e.g. 'name' displays the custom post type name in the dashboard, 'edit' and 'view' are displayed in Edit and View buttons respectively. I think the rest are pretty self explanatory.

In the next arguments:

  • 'public' => true determines the visibility of the custom post type both in the admin panel and front end.
  • 'menu_position' => 15 determines the menu position of the custom post type.
  • 'supports' => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ) determines the features of the custom post type which is to be displayed.
  • 'taxonomies' => array( '' ) creates custom taxonomies. Here it's not defined.
  • 'menu_icon' => plugins_url( 'images/image.png', __FILE__ ) displays the admin menu icon.
  • 'has_archive' => true enables archiving of the custom post type.

Please visit the WordPress Codex register_post_type page for more details on the different arguments used in custom post types.

Step 6: Icon for Custom Post Type

Save a 16x16 pixel icon image in your current plugin folder. This is required for the custom post type icon in the dashboard.

Step 7: Activate the Plugin

Activate the plugin and that's it, you have a new custom post type which has a text editor, publishing and featured image controls, comment control and the custom fields editor.

Step 8: Add a New Item

Click on the Add New option to go to the custom post type editor. Provide a movie title, a review and set a featured image.

Step 9: Publish

Publish the post and click on View Movie Review to view the created movie review in the browser.


Creating Meta Box Fields for Custom Post Types

The meta box mechanism uses the help of the built in WordPress meta box system and helps to add fields required specifically for the custom post types, without requiring the default custom fields in the editor.

Step 1: Registering the Custom Function

Open the Movie-Reviews.php file and add the following code before the PHP end tag. This registers a function to be called when the WordPress admin interface is visited.

add_action( 'admin_init', 'my_admin' );

Step 2: Implementation of the Custom Function

Add an implementation of the my_admin function which registers a meta box and associates it with the movie_reviews custom post type.

function my_admin() {
	add_meta_box( 'movie_review_meta_box',
		'Movie Review Details',
		'display_movie_review_meta_box',
		'movie_reviews', 'normal', 'high'
	);
}

Here add_meta_box is the function used to add meta boxes to custom post types. Explanation of the given attributes:

  • movie_review_meta_box is the required HTML id attribute
  • Movie Review Details is the text visible in the heading of the meta box section
  • display_movie_review_meta_box is the callback which renders the contents of the meta box
  • movie_reviews is the name of the custom post type where the meta box will be displayed
  • normal defines the part of the page where the edit screen section should be shown
  • high defines the priority within the context where the boxes should show

Step 3: Implementation of the display_movie_review_meta_box Function

<?php
function display_movie_review_meta_box( $movie_review ) {
	// Retrieve current name of the Director and Movie Rating based on review ID
	$movie_director = esc_html( get_post_meta( $movie_review->ID, 'movie_director', true ) );
	$movie_rating = intval( get_post_meta( $movie_review->ID, 'movie_rating', true ) );
	?>
	<table>
		<tr>
			<td style="width: 100%">Movie Director</td>
			<td><input type="text" size="80" name="movie_review_director_name" value="<?php echo $movie_director; ?>" /></td>
		</tr>
		<tr>
			<td style="width: 150px">Movie Rating</td>
			<td>
				<select style="width: 100px" name="movie_review_rating">
				<?php
				// Generate all items of drop-down list
				for ( $rating = 5; $rating >= 1; $rating -- ) {
				?>
					<option value="<?php echo $rating; ?>" <?php echo selected( $rating, $movie_rating ); ?>>
					<?php echo $rating; ?> stars <?php } ?>
				</select>
			</td>
		</tr>
	</table>
	<?php
}
?>

This code renders the contents of the meta box. Here we have used an object variable that contains the information of each of the movie reviews displayed in the editor. Using this object we have retrieved the post ID and used that to query the database to get the associated Director's name and Rating which in turn render the fields on the screen. When a new entry is added then the get_post_meta returns an empty string which results in displaying empty fields in the meta box.

Step 4: Registering a Save Post Function

add_action( 'save_post', 'add_movie_review_fields', 10, 2 );

This function is called when posts get saved in the database.

Step 5: Implementation of the add_movie_review_fields Function

function add_movie_review_fields( $movie_review_id, $movie_review ) {
	// Check post type for movie reviews
	if ( $movie_review->post_type == 'movie_reviews' ) {
		// Store data in post meta table if present in post data
		if ( isset( $_POST['movie_review_director_name'] ) && $_POST['movie_review_director_name'] != '' ) {
			update_post_meta( $movie_review_id, 'movie_director', $_POST['movie_review_director_name'] );
		}
		if ( isset( $_POST['movie_review_rating'] ) && $_POST['movie_review_rating'] != '' ) {
			update_post_meta( $movie_review_id, 'movie_rating', $_POST['movie_review_rating'] );
		}
	}
}

This function is executed when posts are saved or deleted from the admin panel. Here after checking for the type of received post data, if it is a Custom Post Type then it checks again to see if the meta box elements have been assigned values and then finally stores the values in those fields.

Step 6: Disabling the Default Custom Fields Option

While creating the custom post type we have defined a function create_movie_review. Remove the custom-fields element from the supports array because this is no longer required. Now if you save the file and open the Movie Reviews editor, you will notice two fields in the meta box named Movie Author and Movie Rating. Similarly you can add other elements too.


Creating a Custom Template Dedicated to Custom Post Types

The proper way to display custom post type data is by using custom templates for each of the custom post types. Here we shall create a template which displays all the Movie Reviews entered using the Movie Review Custom Post Type.

Step 1: Register a Function to Force the Dedicated Template

Open the Movie-Reviews.php file and add the following code before the PHP end tag. This registers a function to be called when the WordPress admin interface is visited.

add_filter( 'template_include', 'include_template_function', 1 );

Step 2: Implementation of the function

function include_template_function( $template_path ) {
	if ( get_post_type() == 'movie_reviews' ) {
		if ( is_single() ) {
			// checks if the file exists in the theme first,
			// otherwise serve the file from the plugin
			if ( $theme_file = locate_template( array ( 'single-movie_reviews.php' ) ) ) {
				$template_path = $theme_file;
			} else {
				$template_path = plugin_dir_path( __FILE__ ) . '/single-movie_reviews.php';
			}
		}
	}
	return $template_path;
}

Here the code searches for a template like single-(post-type-name).php in the current theme directory. If it is not found then it looks into the plugin directory for the template, which we supply as a part of the plugin. The template_include hook was used to change the default behavior and enforce a specific template.

Step 3: Create the Single Page Template File

After saving the previously opened plugin file, create another PHP file named single-movie_reviews.php and put the following code in it.

<?php
 /*Template Name: New Template
 */

get_header(); ?>
<div id="primary">
	<div id="content" role="main">
	<?php
	$mypost = array( 'post_type' => 'movie_reviews', );
	$loop = new WP_Query( $mypost );
	?>
	<?php while ( $loop->have_posts() ) : $loop->the_post();?>
		<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
			<header class="entry-header">

				<!-- Display featured image in right-aligned floating div -->
				<div style="float: right; margin: 10px">
					<?php the_post_thumbnail( array( 100, 100 ) ); ?>
				</div>

				<!-- Display Title and Author Name -->
				<strong>Title: </strong><?php the_title(); ?><br />
				<strong>Director: </strong>
				<?php echo esc_html( get_post_meta( get_the_ID(), 'movie_director', true ) ); ?>
				<br />

				<!-- Display yellow stars based on rating -->
				<strong>Rating: </strong>
				<?php
				$nb_stars = intval( get_post_meta( get_the_ID(), 'movie_rating', true ) );
				for ( $star_counter = 1; $star_counter <= 5; $star_counter++ ) {
					if ( $star_counter <= $nb_stars ) {
						echo '<img src="' . plugins_url( 'Movie-Reviews/images/icon.png' ) . '" />';
					} else {
						echo '<img src="' . plugins_url( 'Movie-Reviews/images/grey.png' ). '" />';
					}
				}
				?>
			</header>

			<!-- Display movie review contents -->
			<div class="entry-content"><?php the_content(); ?></div>
		</article>

	<?php endwhile; ?>
	</div>
</div>
<?php wp_reset_query(); ?>
<?php get_footer(); ?>

Here we have created a basic page template using the loop. The query_posts function retrieves the custom post type elements and displays them using the loop. Of course it is just a basic loop and you can play with it as you want. You can also use proper CSS styles to format the elements accordingly.

Note: You need to create a new page from the dashboard using the newly created template.

Step 4: Images

You need to save two images of star icons 32x32 pixels in your plugin folder. Name them icon.png and grey.png respectively. That's all, now the movie reviews are displayed on a single page sorted by date.

In my next tutorial I shall cover more features of the Custom Post Types like creating an archived page, creating custom taxonomies, custom columns etc. Please feel free to provide your valuable suggestions.

Advertisement