WordPress Custom Post Types The Easy Way

Posted on

Sometimes WordPress doesn’t do exactly what we want it to do. We all know that WordPress is a Blogging Platform but some of you may not know that it can be so much more. WordPress includes many API’s and Hooks to allow us to extend and supplement its already extensive functionality.

What I’m going to show you today is how to add your own custom post types. Below is what a custom post type looks like from the dashboard view.

The Code

Below is a file named custom_post_type_jobs.php. I used this on one of my websites to allow the posting of a new job opening.

<?php 
 
/* Jobs */
function theme_post_type_jobs() {
$labels = array(
			'name' => 'Jobs',
        	'add_new' => 'Add New',
        	'add_new_item' => 'Add New Job',
        	'edit_item' => 'Edit Job',
        	'new_item' => 'New Job',
        	'view_item' => 'View Jobs',
        	'search_items' => 'Search Jobs',
        	'not_found' => 'No Jobs found',
        	'not_fount_in_trash' => 'No Jobs found in Trash'
);
 
$args = array(
			'labels' => $labels, 
			'public' => true, 
			'show_ui' => true,
			'show_in_nav_menus' => false,
			'menu_position' => 5,
			'supports' => array('title', 'editor', 'custom-fields', 'thumbnail', 'revisions'),
			'hierarchical' => true
);
 
register_post_type('job', $args);
 
	register_taxonomy(
		'job-type', 
		'job', 
		array(
			'hierarchical'=>true, 
			'label'=>'Job Type', 
			'query_var'=>true, 
			'rewrite'=>true
		)
	);
}
 
add_action('init', 'theme_post_type_jobs');
 
?>

As you can see, you have the ability to set all types of labels and other options to make the post type fit what you are actually adding into WordPress.

All you must do to use this code is to include this code in your functions.php file either by including it with php’s include(); or pasting it. The only thing you need to do to actually activate it is to call the function below:

theme_post_type_jobs();

If you noticed in the image above, the UI is totally customized with all my labels I set in my code. Here is another picture of what the “Add Job” page looks like.

Customization

The best part about this simple piece of code is that it can be customized. You can have a new post type within 30 seconds of copying this snippet. Wherever you see Jobs or Job, all you must do is replace that with the singular or plural form of the post type that you would like. Say if you would like to add a song post type, all you would need to do is replace every instance of “job” with “song”, or “jobs” with “songs”. It really is that easy.

That’s it for now! Thanks for reading and happy coding!