wordpress-custom-post-types-steroids

WordPress began primarily as a blogging tool because of the “post” paradigm. You could easily create an online journal of running posts for your website. Over time the system matured with the addition of (static) Pages, and tags and categories for posts (for sorting).

With the ability to create custom fields for posts and pages (later), developers began to bastardize the system to create business websites. This was times both hard to deal with (if you creted websites) and frustrating at best. It was also the reason that non-WordPress devs would cry out “WordPress is NOT a CMS, use Drupal or Joomla…” At that time, they actually had a valid point.

Several years ago WordPress added “custom post types“, and taxonomies to the system. This was the point at which WordPress coders could finally tell the Drupalers and Joomla dev’s to shut up – this are the magic pieces that turned WordPress from a “blogging system” to a fully fledged content management system (CMS) for websites.

“Today we’re going to show you how to create and use a custom post type in WordPress with a taxonomy – both code (for intermediate and advanced WP users), and with plugins (for beginners or those that want to save time). Our example will be how to create a portfolio page with a custom post type in WordPress.”

What is a Custom Post Type?

Within WordPress, generally speaking most people know that posts are used for blog posts, and pages are used for pages (like about, contact, services, products, etc.). You can choose to have your posts displayed on the homepage, or a subpage (or not use them at all).

What you can’t easily do is group content together, other than creating pages, and then child pages. To make matters worse, you can’t assign tags and categories to pages (you can only use them on posts).

This led to one of two scenarios for most WP site builders. The first is to put items needing categorization all in posts (including blog posts), but separate them by category.

Such as making all blog posts in the “blog” category, and then services in the “services” category, with sub-categories (when needed) – this scenario is just a very messy affair.

The second way would be to create tons of WordPress pages and sub-pages (with no way to categorize or sort them other than the parent->child relationship of the pages themselves). Some devs used ingenious ways to use custom fields to fit their needs, both in this scenario, and in the first example with posts.

Custom posts types were created to solve this issue.

Everyone is familiar with this image:

WordPress dashboard

The first thing you learn about WordPress is where to go to create, manage, and edit posts, pages, media, links, and comments. By default every WordPress website looks like this on the wp-admin dashboard.

But, once you create a custom post type you’ll see additional selections available in the left sidebar of wp-admin.

In the image below we see the normal WP options for posts, media, links, pages, and comments, but we also see 3 new ones (featured, Market, and Products). These are 3 new “custom post types” that were created within this website.

wordpress-custom-post-types

Now that they have been created, it’s much easier for the client and developer to find and edit content within the website. For this website, everyone knows that posts are only blog posts, pages are static pages (about, contact), featured is for (home page) featured content, Market are the services pages, and products are the products pages.

In this image you see the edit screen for a custom post type “Featured Home”. Looks just like a post or page edit screen – doesn’t it?

add-new-custom-post-type

How Do I Create a New Custom Post Type?

You can easily create a new custom post type via number of methods. We’re going to show you how to do it both with and without code (for both beginners and advanced users).

Using PHP Code for Custom Post types and Taxonomies

It’s easy to create a new custom post type with some code like this:


add_action('init', 'featured_register');

function featured_register() {

$labels = array(
'name' => _x('Featured Home', 'post type general name'),
'singular_name' => _x('Featured Home', 'post type singular name'),
'add_new' => _x('Add New', 'featured item'),
'add_new_item' => __('Add New Featured Item'),
'edit_item' => __('Edit Featured Item'),
'new_item' => __('New Featured Item'),
'view_item' => __('View Featured Item'),
'search_items' => __('Search Featured'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);

$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => get_stylesheet_directory_uri() . '/article16.png',
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','thumbnail')
);

register_post_type( 'featured' , $args );
}

That code would be something that you would add the the functions.php file of your WordPress theme. If you’re a coder, and you want more information on how this works, then check out the register_post_type page in the WP Codex here.

The next thing you would need to do would be to register a taxonomy. A taxonomy is an ordered list of things. Within normal (blog) posts tags and categories are ways to sort posts via taxonomy. By default a custom post type won’t have any taxonomy attributes (unless you define them). So if you’re a coder, you need to use the function register_taxonomy.

Here’s a code example of registering a taxonomy for the custom post type we just created:


register_taxonomy("Type", array("featured"), array("hierarchical" => true, "label" => "Type", "singular_label" => "Type", "rewrite" => true));

That example code creates a taxonomies for “Type”, that could be used to create types of featured content (like tags). In this example for the “Featured” custom post type, maybe Type is a taxonomy item where you add things like “food”, “drink”, “movies” for a website listing featured deals around town.

Taxonomies are helpful for categorizing content, and many times websites have content that would never fit in traditional post or pages. If you have a movie website, you might have a custom post type taxonomy with attributes like “studio”, “actor”, “director”, “rating”, etc. A recipe website might have “ingredients”, “prep time”, “difficulty”, “nationality”, etc.

The last thing you might want to do are add any custom fields you might need for your custom post type edit screen. Examples would be a meta box for clickable URL, an address, phone number, icon URL, expiration date, etc.

We’re not going to delve into the code for that here, but you might want to check out the add meta box function in the WP Codex, or this tutorial on manually creating custom post types.

Using a WordPress Plugin to Create Custom Post Types

The great thing about WordPress is that once somebody figures out how to do something cool with code, somebody else creates a plugin that allows people that don’t know code to do it.

One of the first plugins that came out for creating and managing custom post types was Custom Post Type UI. It’s simple, basic, and it works. I’ve used it a lot over time, but (as usual) I recently found something that works even better.

I’d like to introduce you to the Types plugin, which is brought to you by the same people that create and manage the near famous WPML plugin.

wordpress-types-plugin

Custom post types could be used to build a site with recipes, reviews, classified ads – just about anything. But you could also use it to build a featured content area, a portfolio page, or even a slider area for your homepage. For our purposes today we’re going to build a portfolio page.

In the image below we’re starting on the main settings page of the Types plugin, and we’re going to create a new custom post type and taxonomy.

creating-custom-post-types

To add a new custom post type with Types the first thing we need to do is add in our plural and singular name, and then the slug (that will become the URL), and a brief description.

custom-post-type-setup-1

Next you choose the visibility. If the custom post type is visible, users will be able to add and edit items for it in the WordPress admin dashboard. If it’s hidden, you can add data with code, but users will not be able to add or edit content for that custom post type from the dashboard later.

The meta box after that allows you to select existing taxonomies to use with this custom post type. In this example categories and tags exists because their associated with posts. The Map categorys taxonomy is for a maps plugin we have installed in this test site. Most times you won’t want to use an already registered taxonomy for a custom post type – because they will share search results, and identifiers. If you have 100 tags for your posts, then those 100 tags will be available to your custom post types (and vice versa).

custom-post-type-setup-2

Next you can choose the labels for your custom post type. You can accept the defaults, or edit them to your liking.

custom-post-type-setup-3

Then choose display sections. This is where you choose the default meta boxes that will be available on the edit screens when you add a custom post. By default title and editor are checked (because you need them to properly add content). Beyond that you can choose to have commenting and trackbacks on or off, whether to be able to change the author, whether or not to have an excerpt box, whether or not to have a featured image, custom fields, page attributes, or post formats.

custom-post-type-setup-4

In the advanced section you can choose multiple options – keep in mind that generally speaking, these are for advanced users. You can choose whether or not to use permalinks with your new post type (highly recommended that you do). The option after that is cool because you can choose a custom URL format (if you need to). You can choose whether feeds are on or off for this post type, you can choose whether or not it has an archive (whether it has an index page or not), and whether or not (and where) to show in the admin dashboard menus.

custom-post-type-setup-5

In the last section of advanced settings you can choose whether or not to show a UI to manage this post type, whether or not it’s publicly queryable using post_type queries in code, whether to include in search or not, whether or not it’s hierarchical, whether or not you can export the posts, to show it in nav menus or not, whether or not it can be used in query_var, and the default permalink epmask.

custom-post-type-setup-6

After advanced options you have one more meta box – you can choose a post relationship (if you need to). Generally this is something you won’t need to do, but you could define a parent or child for your custom posts. We’ve expanded the Children option to show that you can only choose from current existing post types. The Types plugin has some great documentation, you can learn about post type relationships here.

custom-post-type-setup-7

When you’ve selected the options you need, click the “save custom post type” button and you’ve created your first custom post type.

In the sidebar, you should now see an entry for your new post type name, along with an “add new” option like this:

Now for our example site, we can add portfolio entries under that new post type sections.

This image is an example of the “add new portfolio” screen. You’ll see (click for full image) that we can add a title, content, an excerpt, a featured image, and we can change the order (if we need to).

add-new-portfolio-item

Although we have 90% of what we need to add portfolio items and create a great portfolio page – what we’re missing is a taxonomy (a way to sort them). We chose not to use tags or categories, because we didn’t want them to be mixed with blog posts.

When you to the “Types -> Custom Types and Taxonomies” sub-menu you’ll see this page. You can see in the image below that we’ve created a post type “Portfolio”, the description, that it’s active, but that it has no taxonomy. So we’re going to create one by clicking the “Add Custom Taxonomy” button.

custom-post-types-and-taxonomies

This is the “add new taxonomy” screen. You’ll notice that much of the choices are the same as adding a new custom post type itself. The first thing we have to do is givee our taxonomy a name and description.

add-new-taxonomy-item

Then we choose whether or not the taxonomy will be visible from the wp-admin dashboard (and it probably should be if you’re going to use it).

taxonomy-visibility

Next choose what post type to use the taxonomy for. We are creating this taxonomy “Type” to use for that Porfolio post type – so that’s what we’ll choose. Note here, although you wouldn’t do it very often, you can use the same taxonomy for different post types.

select-post-types

You can also edit the labels for the taxonomy, although much of the time you’ll probably just use the defaults.

taxonomy-labels

Last you have some advanced taxonomy options, some of which are similar to custom post type advanced options, some are new. The first option is important, whether or not to make the taxonomy hierarchical, in the same way you would have say categories, and sub-categories (or keep them flat like tags). You can choose to rewrite them (for SEO value), whether or not to have hierarchical URL’s, to use show_ui, show in nav menus, or use query_var. You can also choose to use show_tagcloud (or not).

advanced-taxonomy-options-wordpress

When you’re done just click the “save taxonomy” button and you’re done. Now we have one new custom post type, and one new Taxonomy (that we’ve tied to it):

custom-post-type-taxonomy

When you go to the custom post section for “Portfolio” in the WP dashboard now, you’ll see a new sub-menu for “Type” there like this:

new-custom-post-type-taxonomy-item

Visiting the manage “Type” screen, you’ll see that it’s just like adding and removing categories for posts. Since we made this taxonomy item hierarchal, we can now make both types, and sub-types.

add-new-taxonomy-types

How Do I Display Custom Post Types on the Website?

Alright, so we created a custom post type on the backend WP dashboard (Portfolio), and we gave it a Taxonomy to sort by (Type), and we can add new Portfolio items until the cows come home. We can even give them an excerpt, featured image, and description. What you don’t know is how the heck to get them to display within your WordPress theme.

By default WordPress can show (normal blog) posts on your homepage, or you can assign that to an inner page. It can show static “pages”, and you can create some type of menu using a combination of either. However, WordPress by default doesn’t know about any custom post types you’ve created – and there is no theme template out of the box for that type of thing (maybe there should be!).

We’re going to once again show you two options to make your new custom post types display on the front end of your WordPress website. The first with code (for intermediate and advanced), and the second with a plugin (for all levels, but especially beginner).

We’ll start with the coding way…

You Need a Custom Post Type homepage

In WordPress by default under “Settings -> Reading” on the dashboard, you can set where the default (blog) posts are shown. In the image below you see you can choose to show on the homepage your latest posts in normal fashion, or a static page.

If you choose static page, then you must choose which page to show for your homepage, and then which page the default (blog) posts are to be shown upon.

wordpress-settings-reading

We showed that so you would be aware that WordPress offers options for where normal posts are shown, but no options for where to show custom posts that you’ve created.

In order to make that happen, we need to create a custom type “homepage” to show the Portfolio posts.

To do that we need a Custom theme page template that we can use.

We’re using the 2011 theme in our example site, we go to /wp-content/themes/twentyeleven and find “page.php” and download a copy and open it in a text editor, and we add this to the top:


<?php
/*
Template Name: Portfolio
*/
?>

Then we save that file as “page-portfolio.php” and upload that saved file to the theme directory of our webserver.

Now we create a new “Page” in WordPress called “Portfolio”, and on the edit scree, as in the image below in the right under “Page Attributes” we assign the “Portfolio” template to be used for this page and “Publish”.

create-portfolio-homepage

Now we have a published page called “Portfolio” that uses the “Portfolio” page template. At this point all it’s going to do is show whatever text or content we add from the edit screen of this page. It won’t show any actual portfolio items (because we haven’t added the code to do that yet).

Before we get started here’s the code we have to start with for page-portfolio.php:


<?php
/*
Template Name: Portfolio
*/

/*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/

get_header(); ?>

<div id="primary">
<div id="content" role="main">

<?php while ( have_posts() ) : the_post(); ?>

<?php get_template_part( 'content', 'page' ); ?>

<?php comments_template( '', false ); ?>

<?php endwhile; // end of the loop. ?>

</div>
</div>

<?php get_footer(); ?>

It’s pretty basic so far, all it does is get any content we added to the Portfolio page itself like this:

portfolio-page1

We’re going to add some PHP code to page-portfolio.php to make our portfolio posts show on that page. You might want to review the official WordPress page on Post Types, and the Codex Example Using Custom Post Types. Another good reference is the official Codex page for WP_Query.

So, we’re going to add this code to our page-portfolio.php file just before the beginning of the loop (that’s the if have posts, while have posts line):


<?php query_posts(array('post_type'=>'portfolio')); ?>

Now save and upload to your server and you’ll see the portfolio entries appear on your portfolio homepage like this:

portfolio-page2

We don’t show the whole page here, but we have 3 portfolio items, and the title and content for each is displayed in full on this page (the default layout). If this is all you want to do in your layout, your homefree with adding that one line of code to your page template (like we did).

However, for us – we’d like to show only excerpts, we need to add a thumbnail for each item, and we want to show the content of the portfolio page itself, and then the individual portfolio items.

We we’re going to remove that line of code from page-portfolio.php, and then after the first loop (to get portfolio page content), we’re going to add a second wp_query loop to get the list of portfolio posts themselves and display them like this:


<?php
$query_default = new WP_Query( array(
'orderby' => 'menu_order'
,'order' => 'ASC'
,'post_type' => 'portfolio' // custom post type name
,'post_status' => 'publish'
) );
if ( $query_default->have_posts() ) :

while ( $query_default->have_posts() ) : $query_default->the_post();

get_template_part( 'content', 'single' );

endwhile;

else : // else; no posts
_e( 'Nothing published so far.', TEXTDOMAIN_CONSTANT );
endif; // endif; have_posts();

wp_reset_query();
?>

This will get us the Page title and page content for portfolio, AND the titles and contents of all the portfolio items we’ve published so far (which is 3). So – we’re closer to where we want to be, but we’re still showing the full posts.

You see in the code above a convention of the 2011 theme (that your theme might and should follow), the use of template parts. It says for get_template_part to use content, single. If you look in the twentyeleven theme directory you’ll find a file actualy called content-single.php that controls this part of the page.

We’re going to save it as “content-portfolio.php” and save it, and re-upload back to the server in the theme directory.

In that file around line 22 we see this code:


<div class="entry-content">
<?php the_content(); ?>

and all we have to do is change content to excerpt like this:


<div class="entry-content">
<?php the_excerpt(); ?>

In page-portfolio.php we also have to edit the line for get_template_part telling it to get our new content-portfolio.php file instead:


get_template_part( 'content', 'portfolio' );

Now we have our portfolio page title and content, followed by our portfolio items (title and excerpt for each). It’s not pretty, but we can add some CSS layout and code later on.

The next thing is to edit our content-portfolio.php file to show the image for each portfolio item. We uploaded and assigned one for each using the “featured image” box when adding the items.

It’s really simple to do this, all we have to do is add this line of code where we want the image to appear in content-portfolio.php:


<?php the_post_thumbnail('thumbnail'); ?>

As you’ll see on the get_post_thumbnail Codex page, you can specify what size of thumbnail to show (we chose the smallest).

In the end we stripped out the 2011 formatting for the portfolio page (so it would be easier to independently style later) and the code for content-portfolio.php ended up being this (for now):


<?php
/**
* The template for displaying content in the single.php template
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?>

<div class="portitem">

<?php the_post_thumbnail('thumbnail'); ?>

<h1><?php the_title(); ?></h1>

<?php if ( 'post' == get_post_type() ) : ?>
<?php endif; ?>

<?php the_excerpt(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyeleven' ) . '', 'after' => '</div>' ) ); ?>

</div>
<div style="clear:both;"></div>

Now our “Portfolio homepage” is looking a bit more like we want it too:

portfolio-page4

You can see in the image above, we now have a title, and content from portfolio, as well as some basically styled portfolio items, with individual title, excerpt, and featured image for each portfolio post. The Each has a “continue reading” link leading the the individual portfolio single post page – which leads us to the next section…

You Need a Custom Type Single Post Page

By now you should have a much better understanding of all of the theme templates and files involved to add a custom post section to your website. We now know how to create a custom post page template, and then turn that into a custom post type homepage with an archive of the custom posts in it’s own “loop”.

The only thing you haven’t learned yet is how to edit the display of a custom post type single post page. This is the page you see when you click “continue reading” from an excerpt to visit the full post page.

Again – our example uses the 2011 theme, and your theme may be similar in construction (or not). Either way, every theme should have a file called “single.php” in the theme folder.

Download this file in php and “save as” single-customposttype.php, replacing customposttype with your new post type name. We’ll call ours single-portfolio.php as an example. After WordPress 3.0+, WordPress will look for a single post page for your custom post type under single-customposttypename.php, and if it doesn’t find one it will just use single.php. So, once we upload our new single-portfolio.php file to the theme folder on the server, it will now be used for our single portfolio pages.

This is the last missing link to creating an entire custom post type section for your website.

There’s a MUCH Easier Way…

Now that we’ve dragged you all the way through the code, you should understand what it takes to manually setup and display a custom post type in a WordPress theme, on both the back and front end. We have customized countless number of themes in exactly this way over the last few years.

Now, we’d like to introduce you to a new premium plugin called “Views”. The Views plugin is created by the same company that makes the free “Types” plugin. Views makes it possible to create custom post type pages inside a plugin (without knowing any code at all). After seeing all the effort it takes to show custom post types on the front end of a website let me say that again – Views allows you to do this “without knowing any code at all”.

I’m going to walk you through exactly how that works.

Once you’ve installed the Views plugin go to “Views -> New View” in your dashboard sidebar. Rather than learn PHP code, you’re going to point and click your way through creating a “View” that will display your new custom post type the way that you want.

The image below shows the top of the “New View” page, where you have the choice to create either a normal view, or archive view. A normal view is creating a new view to display something, like the view we need to display out Portfolio items. An archive view would be displaying results for an existing WordPress query (which we’ll explain in a minute).

creating-a-view1

When you choose a normal veiw, then click on “edit” to edit the filter and you see this screen. We’re going to choose Posts, and then “Portfolio”, because that’s what we want to display. We’re also going to uncheck the box that says “don’t include current page in query result”, because we want to display the current page content before the taxonomy items (like we did in code before).

We can also chose how to order the posts, we can limit the number of items returned, or choose items to skip. You’ll see at the bottom another button “add another filter term”, which gives more options once you finish this screen for posts or taxonomy.

creating-a-view2

The difference between creating a filter for posts and taxonomy is, the posts filter shows the posts for a post type, the taxonomy shows the taxonomy items. If you want to show both on the same page, you need to create two views, one for each.

creating-a-view3

The “add another filter term” button behaves differently depending on whether you choose posts or taxonomy (different options for each). Basically, you can refine your query even further.

Next you choose your pagination. We want to show all of our portfolio items on a single page, so we’ll choose no pagination.

creating-a-view4

Next you can choose the view layout. We chose grid for our page, but you can also choose unformatted, table, or ordered list / unordered list. You can also choose the number of columns, we chose 4.

creating-a-view5

Then by clicking the “add field” button, you can add any basic or custom fields you’d like to be displayed.

creating-a-view6

We chose the fields we thought we’d be using on our Portfolio page, a featured image, title with a link, excerpt, URL, and the type taxonomy.

creating-a-view7

When you’re all done you just click “save” in the top right to save your new view.

Now that we have a new view created, let’s see how easy it is to insert the custom post type content into our Portfolio page.

We go to the edit screen for “Portfolio” and click the “V” button above the content area toolbar to insert a view, and then click on “Portfolio” under the View section.

The view shortcode is now inserted in our content, and we update and save the page. Before doing this we switched the template back to “default” as we don’t need the special Portfolio template we created earlier when using PHP code by hand.

custom-post-type-shortcode

We view our page for the first time and this is what we have now. The featured image shows, with a clickable linked title, asn excerpt, but then the image URL and type taxonomy just print out below the excerpt. Also we setup the grid for 4 items, and 3 barely fit in the width of the 2011 theme.

custom-post-type-portfolio-page

This is no problem, we just edit our view to remove the things we don’t want, and switch to 2 column display and save to update. No coding at all, the front end page is updated.

insert-shortcode-custom-post-type

About 60 seconds later we were pretty close to what we wanted (in the imge below). We have column style layout, we’re showing a clickable title, featured image, and excerpt.

completed-portfolio-page

In about 10 minutes, we were able to display a custom post type on a WordPress page without using any code, without creating a theme template page, without having to know about “the_loop” or how to display a featured image – we didn’t even need to know any CSS code to switch from default to column based grid view. To do all this earlier in PHP code took about 90 minutes, so using the views plugin was about 90% faster.

The only thing we didn’t do was modify the individual single post pages for the portfolio items, which we can also do with the Views plugin. In future posts we’ll show you how to do that as well. In future posts, we’ll show how to build different kinds of pages and custom websites using Views.

Get more information on the Views plugin here