How To Build A Media Site On WordPress (Part 1)

Advertisement

WordPress is amazing. With its growing popularity and continual development, it is becoming the tool of choice for many designers and developers. WordPress projects, though, are pushing well beyond the confines of mere “posts” and “pages”. How do you go about adding and organizing media and all its complexities? With the introduction of WordPress 3.1, several new features were added that make using WordPress to manage media even more practical and in this tutorial, we’re going to dive in and show you how.

In part one, we’re going to setup custom post types and custom taxonomies, without plugins. After that, we’ll build a template to check for and display media attached to custom posts. Then, in part two, we’ll use custom taxonomy templates to organize and relate media (and other types of content).

As we focus on building a media centric site, I also want you to see that the principles taught in this series offer you a set of tools and experience to build interfaces for and organize many different types of content. Examples include:

  • A “Media” center, of any type, added to an existing WordPress site
  • A repository of videos, third party hosted (e.g. Vimeo, YouTube, etc), organized by topics and presenters
  • A music site, with streaming and song downloads, organized by bands and associated by albums
  • An author-driven Q&A site, with user submitted questions organized by topics and geographical location
  • A recipe site with videos and visitor ratings, organized by category and shared ingredients

In a future tutorial, we will focus on customizing the WordPress backend (with clients especially in mind) to manage a media site and in another tutorial we will use the foundation laid to build a dynamic filtering interface that allows visitors to quickly sort their way through hundreds or even thousands of custom posts.

Requirements

  • WordPress 3.1 – With the release of 3.1, several new features related to the use of custom post types and taxonomies were introduced that are essential to the techniques taught in this series.
  • Basic Familiarity with PHP (or “No Fear”) – To move beyond copying and pasting the examples I’ve given will require a basic familiarity with PHP or, at least, a willingness to experiment. If the code samples below are intimidating to you and you have the desire to learn, then I encourage you to tackle it and give it your best. If you have questions, ask in the comments.

Working Example

In April, 2011 we (Sabramedia, of which I am a co-founder) worked with an organization in Southern California to develop a resource center on WordPress to showcase their paid and free media products. On the front-end, we built a jQuery powered filtering interface to allow visitors to filter through media on-page. We’ll cover the ins and outs of building a similar interface in part three.

ARISE Resource Center
The “Resource Center” on ARISE, with a custom taxonomy filter (“David Asscherick”) pre-selected.

Working With Custom Post Types

By default, WordPress offers two different types of posts for content. First, you have the traditional “post”, used most often for what WordPress is known best for – blogging. Second, you have “pages”. Each of these, as far as WordPress is concerned, is a type of “post”. A custom post type is a type of post that you define.

Note: You can learn more about post types on the WordPress Codex.

In this series, we are going to use custom post types to build a media based resource center. I will be defining and customizing a post type of “resource”.

Setting Up Your Custom Post Type

You can setup your custom post types by code or by plugin. In these examples, I will be setting up the post type by code, storing and applying the code directly in the functions file on the default WordPress theme, Twenty Ten. You can follow along by using a plugin to setup the post types for you or by copying the code samples into the bottom of your theme’s custom functions file (functions.php).

Note: As a best practice, unless you use an existing plugin to create the post types, you may want to consider creating your own WordPress plugin. Setting up custom post types and taxonomies separate from your theme becomes important if and when you want to make major changes to your theme or try a new theme out. Want to save some typing? Use the custom post code generator.

Alright, let’s setup our custom post type. Paste the following code into your theme’s functions.php:

add_action('init', 'register_rc', 1); // Set priority to avoid plugin conflicts

function register_rc() { // A unique name for our function
 	$labels = array( // Used in the WordPress admin
		'name' => _x('Resources', 'post type general name'),
		'singular_name' => _x('Resource', 'post type singular name'),
		'add_new' => _x('Add New', 'Resource'),
		'add_new_item' => __('Add New Resource'),
		'edit_item' => __('Edit Resource'),
		'new_item' => __('New Resource'),
		'view_item' => __('View Resource '),
		'search_items' => __('Search Resources'),
		'not_found' =>  __('Nothing found'),
		'not_found_in_trash' => __('Nothing found in Trash')
	);
	$args = array(
		'labels' => $labels, // Set above
		'public' => true, // Make it publicly accessible
		'hierarchical' => false, // No parents and children here
		'menu_position' => 5, // Appear right below "Posts"
		'has_archive' => 'resources', // Activate the archive
		'supports' => array('title','editor','comments','thumbnail','custom-fields'),
	);
	register_post_type( 'resource', $args ); // Create the post type, use options above
}

The code above tells WordPress to “register” a post type called “resource”. Then, we pass in our options, letting WordPress know that we want to use our own labels, that we want our post type to be publicly accessible, non-hierarchal, and that we want it to show up right below “posts” in our admin menu. Then, we activate the “archive” feature, new in WordPress 3.1. Finally, we add in “supports”: the default title field, the WordPress editor, comments, featured thumbnail, and custom fields (I’ll explain that  later).

Note: For more information on setting up the post type and for details on all the options you have (there are quite a few available), refer to the register_post_type function reference on the WordPress Codex.

If the code above was successful, you will see a new custom post type, appearing below “Posts” in the WordPress admin menu. It will look something like this:

Screenshot
A view of the WordPress Admin, after adding a custom post type

We’re in good shape! Next, let’s setup our custom taxonomies.

Working With Custom Taxonomies

A “taxonomy” is a way of organizing and relating information. WordPress offers two default taxonomies, categories and tags. Categories are hierarchal (they can have sub-categories) and are often used to organize content on a more broad basis. Tags, are non-hierarchal (no sub-tags) and are often used to organize content across categories.

A “term” is an entry within a taxonomy. For a custom taxonomy of “Presenters”, “John Smith” would be a term within that taxonomy.

In this series, we will be creating two different custom taxonomies to organize the content within our resource center.

  • Presenters – Each media item in our resource center will have one or more presenters. For each presenter, we want to know their name and we want to include a short description. Presenters will be non-hierarchal.
  • Topics – Our resource center will offer media organized by topics. Topics will be hierarchal, allowing for multiple sub-topics and even sub-sub-topics.

Note: Interested in working with more than the title and short description? Take a look at How To Add Custom Fields To Custom Taxonomies on the Sabramedia blog.

Setting Up Presenters

Our goal with presenters is to create a presenter profile, referenced on the respective media pages, that will give more information about the presenter and cross-reference other resources that they are associated with.

Add the following code to your theme’s functions.php file:

$labels_presenter = array(
	'name' => _x( 'Presenters', 'taxonomy general name' ),
	'singular_name' => _x( 'Presenter', 'taxonomy singular name' ),
	'search_items' =>  __( 'Search Presenters' ),
	'popular_items' => __( 'Popular Presenters' ),
	'all_items' => __( 'All Presenters' ),
	'edit_item' => __( 'Edit Presenter' ),
	'update_item' => __( 'Update Presenter' ),
	'add_new_item' => __( 'Add New Presenter' ),
	'new_item_name' => __( 'New Presenter Name' ),
	'separate_items_with_commas' => __( 'Separate presenters with commas' ),
	'add_or_remove_items' => __( 'Add or remove presenters' ),
	'choose_from_most_used' => __( 'Choose from the most used presenters' )
);

register_taxonomy(
	'presenters', // The name of the custom taxonomy
	array( 'resource' ), // Associate it with our custom post type
	array(
		'rewrite' => array( // Use "presenter" instead of "presenters" in the permalink
			'slug' => 'presenter'
			),
		'labels' => $labels_presenter
		)
	);

Let’s break that down. First, we setup the labels to be used when we “register” our taxonomy. Then, we give it a name, in this case “presenters”, and assign it to the post type of “resource”. If you had multiple post types, you would add them in with a comma, like this:

array( 'resource', 'other-type' ), // Associate it with our custom post types

After that,  we change the URL (or “permalink”) to satisfy our desire for grammatical excellence. Rather than being “/presenters/presenter-name” we update the “slug” (what is a slug?) to remove the “s” so that the permalink will read “/presenter/presenter-name”.

In our example, you should now notice a new menu option labeled “Presenters” under “Resources” in the admin sidebar. When you go to create a new resource you should also notice a meta box on the right side that looks like this:

Screenshot
My custom taxonomy of “Presenters” now shows up between the “Publish” box and “Featured Image”.

Note: To learn more about setting up custom taxonomies and the options available, take a look at the register_taxonomy function reference on the WordPress Codex.

Setting Up Topics

Our goal with topics is to allow for a hierarchal set of topics and sub-topics, each with their own page, showing the resources that are associated with each respective topic.

Add the following code to your theme’s functions.php file:

$labels_topics = array(
	'name' => _x( 'Topics', 'taxonomy general name' ),
	'singular_name' => _x( 'Topic', 'taxonomy singular name' ),
	'search_items' =>  __( 'Search Topics' ),
	'all_items' => __( 'All Topics' ),
	'parent_item' => __( 'Parent Topic' ),
	'parent_item_colon' => __( 'Parent Topic:' ),
	'edit_item' => __( 'Edit Topic' ),
	'update_item' => __( 'Update Topic' ),
	'add_new_item' => __( 'Add New Topic' ),
	'new_item_name' => __( 'New Topic Name' ),
);

register_taxonomy(
	'topics', // The name of the custom taxonomy
	array( 'resource' ), // Associate it with our custom post type
	array(
		'hierarchical' => true,
		'rewrite' => array(
			'slug' => 'topic', // Use "topic" instead of "topics" in permalinks
			'hierarchical' => true // Allows sub-topics to appear in permalinks
			),
		'labels' => $labels_topics
		)
	);

That was easy enough! The code above is similar to setting up presenters, except this time we are using a few different labels, specific to hierarchal taxonomies. We set hierarchal to true (it’s set to “false” by default), we update the slug to be singular instead of plural, then, just before referencing our labels, we set the rewriting to be hierarchal. A hierarchal rewrite allows permalinks that look like this: /topic/topic-name/sub-topic-name.

With the above code implemented, you should notice another option below “Resources” in the WordPress admin and a new meta box that looks like this:

Screenshot
My custom taxonomy of “Topics” now shows up, albeit a bit empty looking, below “Presenters”.

Adding Custom Fields To Custom Post Types

In many cases, the “title” and “editor” (the default content editor in WordPress) aren’t going to be enough. What if you want to store extra information about a particular custom post? Examples might include:

  • Duration of a media file – HH:MM:SS format, useful to pre-populate your media player with the duration on page load.
  • Original recording date – Stored as a specific date with day, month, and year.

We call this “meta” information and it is a set of details that are specific to the individual item and usually make the most sense to store as meta data, as opposed to terms within a custom taxonomy. While you could put all these details in the “editor” field, it gives you very little flexibility with how this is displayed within your template.

So, let’s setup some custom fields. Use the custom fields interface at the bottom of an individual custom post to add some extra details about your custom post.

For our example, we’re going to add two fields. For each field, I will list the name, then an example value:

  • recording_length - Example: 00:02:34
  • recording_date – Example: March 16, 2011

Here’s how that looks after adding two custom fields:

Screenshot
An example of the custom fields interface after adding two “keys” and their respective “values”

Note: The default custom fields interface can be a bit limiting. If you’d like to make use of a plugin, try More Fields. The functionality is the same (just be mindful of what you name your custom fields) – a plugin typically offers you a better interface. If you want to build your own interface, take a look at WP Alchemy. To learn more about using custom fields, take a look at using custom fields on the WordPress Codex.

Custom Taxonomies vs. Custom Fields

At this point, you may run into a situation where you’re uncertain whether a particular piece of information should be stored as a custom taxonomy or as a custom field. Let’s use the recording date as an example. If we were to log the complete date, then it would probably make the most sense to store it within a custom field on the individual item. If we were to just use the year, though, we could store it as a term within a custom taxonomy (we’d probably call it “year”) and use it to show other resources recorded that same year.

The question is whether or not you want to relate content (in our case, “resources”) by the information you’re considering. If you don’t see any need to relate content (and don’t have plans to) then a custom field is the way to go. If you have a need to relate content or see a potential need down the road, then a custom taxonomy is the way to go.

Media Storage – WordPress vs. Third Party

Now that we have our custom post type and custom taxonomies in place, it’s time to upload some media. Our goal is to make this as simple a process for the end-user as possible. There are two ways that we can manage the media, either directly within WordPress or via third party.

  • WordPress Managed - WordPress has a media management system built-in. You can upload media directly from your post type interface or from the “media” section in the WordPress admin. If storage or bandwidth becomes an issue, you can use a plugin (such as WP Super Cache) to offload the storage of the media to a third party content delivery network (CDN) to optimize delivery speed and save on bandwidth.
  • Third Party – Going this route, you can use a media hosting service like YouTube, Vimeo, Scribd (PDFs), Issuu (ebooks), or any media hosting service that offers you an embed option.

Going the internal route, the media is stored inside of WordPress and associated with the individual custom post. We then access it as an attachment within the template. Going the third party route, we get the embed code (or the media ID) and store it inside of WordPress within a custom field. We’ll look at examples of both options further on.

Note: Working with images? Take a look at a recent Smashing article that covers better image management with WordPress.

Preparing The Stage – Adding New Media

We’re about to start working with the templates. Before we do that, though, we need to have some media to work with within our new custom post type. Before proceeding, make sure you’ve done the following:

  • Create a new “resource” post (or whatever your post type may be) and give it a title and a description in the main content editor.
  • Associate your resource with a non-hierarchical custom taxonomy you’ve created (e.g. A presenter named “Jonathan Wold”).
  • Associate your resource with a hierarchical custom taxonomy you’ve created (e.g. A topic of “Family” and a sub-topic of “Children”)
  • Add one or more custom fields with a unique “key” and “value” (e.g. a key of “recording_duration” and a value of “00:02:34″).
  • Upload a video file to your custom post using the WordPress media manager (click the “video” icon just below the title field and right above the editor).

Note: If you’re hosting your videos via third party, create a custom field to hold either the entire embed code or the ID of the video. I’ll give you an example using Vimeo a bit later that will use the video ID.

Note #2: Depending on your hosting provider, you may run into trouble with a default upload limit, often 2MB or 8MB. Check out how to increase the WordPress upload limit.

After you’ve created a new post, previewing it should show you a screen, depending on your theme, will look something like this:

Screenshot
A preview of my custom post, displaying title and description, on the Twenty Ten theme.

Note: If you preview your post and get a “404″ error, you may need to update your Permalinks. From the WordPress Admin, Go to “Settings”, then “Permalinks”, and click “Save Changes”. Refresh and you should be good to go.

Displaying Our Media – Working With Custom Post Templates

If you previewed your custom post, you probably saw something similar to what I showed in my example – not much. Where are the custom taxonomy terms, custom fields, and videos? Missing – but not for long! In the following steps, we’re going to create a custom template that tells WordPress what data to display and how to display it.

Creating A Custom Post Type Template

The WordPress template engine has a hierarchy that it follows when deciding what theme template it uses to display data associated with a post. In the case of our “resource” post type, the WordPress hierarchy (as of 3.1) is as follows:

  • single-resource.php – WordPress will check the theme folder for a file named single-resource.php, if it exists, it will use that file to display the content. For different post types, simple replace “resource” with the name of your custom post type.
  • single.php – If no post type specific template is found, the default single.php is used. This is what you probably saw if you did an early preview.
  • index.php – If no single template is found, WordPress defaults to the old standby – the index.

I’ll be using minimal examples for each of the templates, modified to work with Twenty Ten. Each example will replace and build on the previous example. Expand to your heart’s content or copy the essentials into your own theme.

To get started with our example, create a file called single-resource.php and upload it to your theme folder. Add the following code:

<?php get_header(); ?>

	<div id="container">
		<div id="content">
		<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

			<div class="resource">
				<h1 class="entry-title"><?php the_title(); ?></h1>
				<div class="entry-content">
					<?php the_content();?>
				</div>
			</div>

		<?php endwhile; ?>
		</div>
	</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

The code above will give you a rather unexciting, but working template that will display the title and content (drawn directly from the main editor). What about our custom fields? Let’s add them in next.

Replace the code in single-resource.php with the following:

<?php get_header(); ?>

<?php // Let's get the data we need
	$recording_date = get_post_meta( $post->ID, 'recording_date', true );
	$recording_length = get_post_meta( $post->ID, 'recording_length', true );
?>

	<div id="container">
		<div id="content">
		<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

			<div class="resource">
				<h1 class="entry-title"><?php the_title(); ?></h1>
				<div class="entry-meta">
					<span>Recorded: <?php echo $recording_date ?> | </span>
					<span>Duration: <?php echo $recording_length ?> </span>
				</div>
				<div class="entry-content">
					<?php the_content();?>
				</div>
			</div>

		<?php endwhile; ?>
		</div>
	</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

We’re making progress! Now, using the examples above, you should see the date your resource was published and the duration of the media file.

Let’s take a look at how that works. In WordPress, data stored in custom fields can be accessed several ways. Here, we are using a function called get_post_meta. This function requires two parameters, the unique ID of the post you want to get the data from and the name of the field (its “key”) whose data you’re after. Here’s the code again:

$recording_date = get_post_meta( $post->ID, 'recording_date', true );

First, we set a variable with PHP – we name it “$recording_date”. Then, we use the “get_post_meta” function. Remember, it needs two parameters, ID and the “key” of the field we want. “$post->ID” tells WordPress to use the ID of the post it is currently displaying. If we wanted to target a specific post, we’d put its ID instead:

$recording_date = get_post_meta( 35, 'recording_date', true ); // Get the date from post 35

The next parameter is the “key”, or “name” of our custom field. Be sure you get that right. The last parameter tells the function to return the result as a single “string” – something that we can use as text in our template below. To display our data in the template, we write:

<?php echo $recording_date ?>

Ok, let’s keep going and get our custom taxonomies showing up.

Replace the code in single-resource.php with the following:

<?php get_header(); ?>

<?php // Let's get the data we need
	$recording_date = get_post_meta( $post->ID, 'recording_date', true );
	$recording_length = get_post_meta( $post->ID, 'recording_length', true );
	$resource_presenters = get_the_term_list( $post->ID, 'presenters', '', ', ', '' );
	$resource_topics = get_the_term_list( $post->ID, 'topics', '', ', ', '' );
?>

	<div id="container">
		<div id="content">
		<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

			<div class="resource">
				<h1 class="entry-title"><?php the_title(); ?></h1>
				<div class="entry-meta">
					<span>Recorded: <?php echo $recording_date ?> | </span>
					<span>Duration: <?php echo $recording_length ?> | </span>
					<span>Presenters: <?php echo $resource_presenters ?> | </span>
					<span>Topics: <?php echo $resource_topics ?></span>
				</div>
				<div class="entry-content">
					<?php the_content();?>
				</div>
			</div>

		<?php endwhile; ?>
	 	</div>
 	</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Now we’re starting to get more dynamic. You should see your custom fields and, assuming that your custom post has “presenters” and “topics” associated with it, you should see a list of one or more custom taxonomy terms as links. If you clicked the link, you probably saw a page that didn’t look quite what you expected – we’ll get to that soon. Check out get_the_term_list on the WordPress Codex to learn more about how it works.

Adding A Media Player

Now that we have some basic data in place, it’s time to add our media player. In this example, we will be working with the JW Media Player, a highly customizable open-source solution.

Installing JW Media Player

You can access basic installation instructions here. I recommend the following steps:

  1. Download the player from the Longtail Video website.
  2. Create a folder within your theme to hold the player files – In this case, I’ve named the folder “jw”.
  3. Upload jwplayer.js and player.swf to the JW Player folder within your theme.

JW Player is now installed and ready to be referenced.

Now, replace the code in single-resource.php with the following:

<?php get_header(); ?>

<?php // Let's get the data we need
	$recording_date = get_post_meta( $post->ID, 'recording_date', true );
	$recording_length = get_post_meta( $post->ID, 'recording_length', true );
	$resource_presenters = get_the_term_list( $post->ID, 'presenters', '', ', ', '' );
	$resource_topics = get_the_term_list( $post->ID, 'topics', '', ', ', '' );

	$resource_video = new WP_Query( // Start a new query for our videos
	array(
		'post_parent' => $post->ID, // Get data from the current post
		'post_type' => 'attachment', // Only bring back attachments
		'post_mime_type' => 'video', // Only bring back attachments that are videos
		'posts_per_page' => '1', // Show us the first result
		'post_status' => 'inherit', // Attachments require "inherit" or "all"
		)
	);
?>

	<div id="container">
		<div id="content">
		<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

			<div class="resource">
				<h1 class="entry-title"><?php the_title(); ?></h1>
				<div class="entry-meta">
					<span>Recorded: <?php echo $recording_date ?> | </span>
					<span>Duration: <?php echo $recording_length ?> | </span>
					<span>Presenters: <?php echo $resource_presenters ?></span>
				</div>
				<div class="entry-content">
					<?php while ( $resource_video->have_posts() ) : $resource_video->the_post(); ?>
						<p>Video URL: <?php echo $post->guid; ?></p>
					<?php endwhile; ?>

					<?php wp_reset_postdata(); // Reset the loop ?>

					<?php the_content(); ?>
				</div>
			</div>

		<?php endwhile; ?>
		</div>
	</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Note: You may notice the somewhat mysterious reference to “wp_reset_postdata”. We are creating a loop within a loop and, to prevent strange behavior with template tags like “the_content” (try removing “wp_reset_postdata” to see what happens), we need to run a reset after any new loops we add within the main loop. Learn more about the loop on the WordPress Codex.

Now we’re getting somewhere! If everything went as expected, you should see a direct, plain text URL to your video. That’s not very exciting (yet), but we want to make sure we are getting that far before we add in the next step – the player.

If you’re having trouble at this point, check back through your code and look for any mistakes that may have been made. If you are trying to vary widely from this example, simplify your variations and start as close to this example as you can – get that to work first then branch back out.

With the URL to our video available, we are ready to add in the player. Let’s go!

Replace the code in single-resource.php with the following:

<?php get_header(); ?>

<?php // Let's get the data we need
	$recording_date = get_post_meta( $post->ID, 'recording_date', true );
	$recording_length = get_post_meta( $post->ID, 'recording_length', true );
	$resource_presenters = get_the_term_list( $post->ID, 'presenters', '', ', ', '' );
	$resource_topics = get_the_term_list( $post->ID, 'topics', '', ', ', '' );

	$resource_video = new WP_Query( // Start a new query for our videos
	array(
		'post_parent' => $post->ID, // Get data from the current post
		'post_type' => 'attachment', // Only bring back attachments
		'post_mime_type' => 'video', // Only bring back attachments that are videos
		'posts_per_page' => '1', // Show us the first result
		'post_status' => 'inherit', // Attachments require "inherit" or "all"
		)
	);
?>

	<div id="container">
		<div id="content">
		<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

			<div class="resource">
				<h1 class="entry-title"><?php the_title(); ?></h1>
				<div class="entry-meta">
					<span>Recorded: <?php echo $recording_date ?> | </span>
					<span>Duration: <?php echo $recording_length ?> | </span>
					<span>Presenters: <?php echo $resource_presenters ?> | </span>
					<span>Topics: <?php echo $resource_topics ?></span>
				</div>

				<div class="entry-content">
				<?php while ( $resource_video->have_posts() ) : $resource_video->the_post(); // Check for our video ?>
					<div id="player">
						<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/jw/jwplayer.js"></script>
						<div id="mediaspace">Video player loads here.</div>
						<script type="text/javascript">
						    jwplayer("mediaspace").setup({
						        flashplayer: '<?php bloginfo( 'stylesheet_directory' ); ?>/jw/player.swf',
						        file: '<?php echo $post->guid; ?>',
						        width: 640,
						        height: 360
						    });
						</script>
					</div>
				<?php endwhile; ?>

				<?php wp_reset_postdata(); // Reset the loop ?>

				<?php the_content(); ?>
				</div>
			</div>

		<?php endwhile; ?>
		</div>
	</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Note carefully the assumptions I’m making in the code above. First, I am assuming that you are storing the JW player files in a folder called “jw” inside the WordPress theme folder of the currently activated theme. If you load the page and the player is not working (and you did have the video URL displaying in the previous step), view the source code on your page, copy the URLs that WordPress is generating to your respective JW player files (jwplayer.js and player.swf) and try accessing them in your browser to make sure each is valid. If there is a problem, update your references accordingly.

Otherwise, there you have it! Your video details and the video itself is now displaying on the page and you should see something like this:

Screenshot
A view of the player, complete with title, description, custom field values and custom taxonomies terms.

Note: There is a lot that you can do to customize the appearance and behavior of the JW Player. A good place to start is the JW Player Setup Wizard. Customize the player to your liking, then implement the code changes in your template accordingly.

Using Vimeo Instead

Let’s say you wanted to use Vimeo, instead of uploading the videos into WordPress. First, you need to add a custom field to store the ID of your Vimeo video. Assuming you’ve done that, and assuming that you’ve entered a valid Vimeo ID in your custom field (we named the field “vimeo_id” in our example), the following code will work:

<?php get_header(); ?>

<?php // Let's get the data we need
	$recording_date = get_post_meta( $post->ID, 'recording_date', true );
	$recording_length = get_post_meta( $post->ID, 'recording_length', true );
	$resource_presenters = get_the_term_list( $post->ID, 'presenters', '', ', ', '' );
	$resource_topics = get_the_term_list( $post->ID, 'topics', '', ', ', '' );

	$vimeo_id = get_post_meta( $post->ID, 'vimeo_id', true );
?>

	<div id="container">
		<div id="content">
		<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

			<div class="resource">
				<h1 class="entry-title"><?php the_title(); ?></h1>
				<div class="entry-meta">
					<span>Recorded <?php echo $recording_date ?> | </span>
					<span>Duration: <?php echo $recording_length ?> | </span>
					<span>Presenters: <?php echo $resource_presenters ?> | </span>
					<span>Topics: <?php echo $resource_topics ?></span>
				</div>

				<div class="entry-content">
					<?php if ($vimeo_id) { // Check for a video ?>
						<iframe src="http://player.vimeo.com/video/<?php echo $vimeo_id; ?>?byline=0&title=0&portrait=0" width="640" height="360" frameborder="0" class="vimeo"></iframe>
					<?php } ?>

					<?php the_content(); ?>
				</div>
			</div>

		<?php endwhile; ?>
		</div>
	</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

We use “$vimeo_id” to retrieve and store the ID from our custom field (named “vimeo_id”, in this case) and then, in the code below, we first check to make sure the $vimeo_id field has data in it, then we use Vimeo’s iframe code (details here) to load the video.

Screenshot
In Vimeo’s case, the ID is a series of numbers (notice the selected text) after “vimeo.com/”.

Conclusion

And that concludes part one! You’ve learned how to setup custom post types and custom taxonomies without using plugins. You’ve also learned how to setup custom fields and display their data, along with a video player and custom taxonomy terms, within a custom post template. In part two, we’ll look at how to customize the custom taxonomy templates and make them a whole lot more useful.

Credits

Though this article keeps things basic, the conclusions in part two and a lot of the techniques developed in conjunction with the projects that inspired this series would have been much more difficult without the help of the WordPress Stack Exchange community. If you have a question directly related to this post, ask it here. If you have anything else WordPress related, though, WPSE is the place to go. Also, a big thank you to Joshua, Nick, CJ, and Matt for their many hours spent reviewing, testing code samples, and providing feedback while I worked on this series.

↑ Back to top

Jonathan Wold is the husband of a beautiful redhead named Joslyn and the father of a baby boy named Jaiden. He works at Sabramedia, a web design and development company that specializes in WordPress powered media sites. He is also a core developer and evangelist for Newsroom, a newspaper paywall and CMS built for the newspaper industry.

  1. 1

    This is great! Can’t wait for the next part.

    1
  2. 2

    Suddenly inspired!

    June 2, 2011 7:46 am

    Delighted to see this article – bookmarked to read properly tonight, really looking forward to part 2 – thank you!

    0
  3. 3

    Does anyone know that this is a million times easier in Drupal? Just curious, never see anything about Drupal.

    0
    • 4

      I sure would like to see some Drupal tutorials on smashingmag. I like WordPress for small sites but I would like to start learning how to set up larger sites and I’ve seen Drupal 7 at work and it seems easier for those setups.

      0
    • 5

      I’d love to see some Drupal tutorials as well. That is something I’m yet to properly sink my teeth in to.
      But this is fantastic, it has helped clarify a few things for me that I’m looking forward to testing tomorrow.

      0
    • 6

      Agree 100%. I use Drupal for most sites I build, small to large, and I would love to see some more attention toward it. I like WordPress, and the new features of 3.x are very welcome, but Drupal is just a kick-butt CMS that has done so many of the now-new-and-wowing-people-in-WP things for several versions now. And 7.x is just amazing. As said, I like WordPress, but I don’t want the dev community to become too WP-centric. More Drupal material would be great.

      0
      • 7

        I love wordpress but this is much easier, must faster and much better done with Drupal

        0
    • 8

      Agree. Doing any sort of coding in WordPress is a nightmare compared to Drupal. If you want a simple blog-type site up and running quickly, WordPress isn’t too bad. For everything else, use Drupal.

      0
    • 9

      WordPress is still much better!

      0
    • 10

      But in wordpress you can use a plugin. I know that it’s better don’t use it, but anyone with no programming skills (like me, i’m a designer) can do it easily.

      0
    • 11

      Drupal sólo vale si el administrador es un usuario avanzado, si no, mucho mejor wordpress.

      salu2

      1
  4. 12

    One of the most thorough, complete tutorials on WordPress I’ve ever seen. Thanks, Jonathon.

    0
  5. 14

    You covered it brilliantly well .
    Practical and equally insightful…looking forward to next in series .

    0
    • 15

      Thank you, Aftab! Part 2 will be out shortly and I look forward to your feedback on it!

      0
  6. 16

    excellent excellent article. I was just working on something similar to this and now I am going to start from scratch with your help :)

    Thank you!

    0
    • 17

      Garrett, thank you for your kind words. My hope was to make this be as useful as possible, both for folks working on projects already up and running and those starting from scratch. I’m glad to hear that this has been helpful to you and I’m sure you’ll enjoy part 2!

      0
  7. 18

    Beautiful Tutorial, excellent code factoring and utilization of the WordPress framework.

    0
  8. 19

    Does anyone know what wordpress plugin was used to filter multiple items like that on a single page?

    0
    • 20

      John, the filtering uses a combination of custom taxonomies, custom fields, as well as price data drawn via the Shopify API. The interface itself is done using a custom plugin we built with jQuery. We’ve considered releasing the plugin and technique for public use and may do so if there is enough interest.

      1
      • 21

        I can’t wait for 3rd part of tutorial. Releasing the plugin will be awesome…

        0
        • 22

          Whoops, this first tutorial was originally written as one tutorial and part 1 in a 3 part series. It was so long, though, that we split it into 2 parts. The other tutorials, on customizing the backend and then building the filtering interface are planned for the future. I forgot to update the reference to them in the article before it was published :). I am weighing in your vote on the plugin release, though. We wanted to gauge the interest before spending the time to put it together.

          -1
          • 23

            I am extremely interested in a plugin like this, as well as even paying for a plugin with the same functionality.

            Really fantastic work.

            0
          • 24

            I am also interested in getting the plugin and even paying for it.

            0
          • 25

            Nice work. The jQuery filtering interface would be a sweet addition. I hope you get around to it soon.

            0
      • 26

        Louis-Philippe Dea

        February 2, 2012 1:57 pm

        Same thing here John, I’m really interested in the plugin. Do you have some updates about it ?

        0
  9. 27

    Excellent article. I am wondering if this works with the HTML5 version of the JW Video Player? My PHP is not great and I couldn’t tell from the example code whether or not it would still work.

    0
    • 28

      Matt, thank you! The JW Player example I used is based on their latest method and makes use a new API to automatically determine whether to show the flash or HTML 5 version of the player. On flash supported browsers, it uses flash, and if there is no support, it uses HTML 5.

      0
  10. 29

    wonderful! thank you so much for taking the time for writing this extremely useful (for me at least) article. already made good use of the info in it for a site I am building.

    0
    • 30

      Raffi, it was an extensive article to write and I’m very happy to hear that it’s already being put to good use. Please do report back and show me what you build with it!

      0
  11. 31

    wow! this is a truly amazing article! Please publish more of these useful posts :)
    Back in the days smashingmagazine used to post a lot more of these types of posts, keep them coming!

    0
  12. 32

    Great article! I have already begun revamping my site with your tips. The custom post types and taxonomies will really help me take my site to the next level.

    Thanks!

    0
    • 33

      Hey Victor, thanks for stopping by! I appreciate your early review of the article. I’m looking forward to seeing how you put it into practice!

      0
  13. 34

    Custom post types are amazing, HOWEVER, and I stress the however part for good reason, they do as of 3.1 contain a serious bug that needs to be worked out. The bug in question is a tricky one to discover and 9 times out of 10 most people will never have to worry about it but there are always those like me who go all out and encounter it.

    The bug happens when you have about 1,000+ (Number varies depending on server settings) entries inside of a custom post type, for instance I had a custom post type called Tv Shows and I added 20,000 entries into that post type (Lots I know, I did say I was hardcore).

    Anyway when you click on your custom post type menu in the admin panel WordPress encounters a paging flaw, WordPress will query and return the post meta data for ALL the posts contained in your custom post type and not just the first 20 like it should.

    This is a huge problem for larger data sets because you encounter a resource limit error after a 30 second page timeout happens, so to clarify, what should happen (behind the scenes) when you click your custom post type, WordPress will return 20 results to look at and should only gather post meta data for those 20 results but as it stands in 3.1 it returns some post meta for ALL your posts contained in the custom post type.

    Custom post types are very powerful but watch out for this if your adding large amounts of posts to your site because you’ll encounter this issue. Hopefully they’ll fix it in one of the nightly builds soon so I can continue testing my custom post types with 20,000+ posts to see how it stands up.

    0
    • 35

      Sorry forgot to mention that this bug only happens when you have your hierarchical setting set to true in your custom post type, when it is set to false everything works perfect.

      0
      • 36

        Adam, thank you for mentioning that! I hadn’t run into that in any of our development thus far. Have you submitted or identified a ticket for the bug?

        0
        • 37

          I tried to submit a ticket for it but I was unable to signup to get an account for some odd reasons. I might try again today now that its on the top of my head.

          0
  14. 38

    David Williamson

    June 2, 2011 2:02 pm

    I am just trying to get my head around how to utilise custom post types to enhance some audio uploads, so this has been a really useful article. There’s a lot of information to take in, but it is clearly explained with an in-depth and realistic example. I can see a lot of effort has gone into this, thanks for making it publicly available. Looking forward to Part 2.

    0
  15. 39

    Thank You !!! great work
    I will try it …

    0
  16. 40

    Final Cut Studio

    June 2, 2011 2:49 pm

    This is fantastic and very well put together! I’m definitely going to be needing this in the very near future. Your tips and notes with links to other resources are awesome! Thanks so much for sharing this with everyone! Well done, Jonathan!

    Best -
    Robert Ricker

    0
  17. 41

    Wonderful post showing off the awesome post types feature, along with custom taxonomies. One thing I would add is that you use the add_meta_box() function (http://codex.wordpress.org/Function_Reference/add_meta_box) to create native boxes in the UI for displaying and storing custom fields.

    The functionality of this is the same as using the custom fields boxes, but it looks a bit neater, especially useful if you are doing something for a client.

    0
  18. 42

    Very useful, detailed article that will be put to good use immediately. Always on the look out to make things easier for my clients – which in turns makes us as developers/designers look great. Cheers.

    0
  19. 43

    Michael Raffaele

    June 2, 2011 3:56 pm

    Really good article. I have been meaning to start experimenting with custom post types but just haven’t had the necessity for them just yet.

    You’ll code examples will make it a breeze when I finally do get around to giving it a try.

    0
  20. 44

    Filipe Valente

    June 2, 2011 6:04 pm

    A video tutorial would have been so much better then just an article

    0
  21. 45

    one more example can been seen @ the media page at samasamtennis.com

    0
  22. 46

    hm … and of what greater value is NOT using oEmbeds? Nobody needs to find out about some IDs and stuff – instead you can simply drop the URL of the video platform; and tadaa – WP does it all by itself!

    cu, w0lf.

    0
  23. 47

    Heading towards local host and try it out.

    0
  24. 48

    Vincent Hasselgård

    June 2, 2011 11:03 pm

    Thanks for a great article! I’m looking forward to part two. I’m planning to build a CMS on WordPress and custom post types and taxonomies are going to be very useful :) Lots of great links to other articles where needed too.

    Again, thanks a bunch!

    0
    • 49

      Vincent, you are most welcome. I think you’ll really enjoy part two! Look forward to let and do let me know what you think!

      0
  25. 50

    This is a really fantastic and very helpful post, thanks a lot! I’ve learnt from this post which I have struggled with for ages. There’s a lot and can’t wait to put it into practice. Cheers, bigandy

    0
    • 51

      Bigandy, thank you for your feedback and kind words! I’m glad to hear this has been a help to you and that you’ll be able to put it into practice. Please do let me know what you develop!

      0
  26. 52

    Thank you!

    I am new to PHP and I have been looking for a good way to practice. This along with the PHP manual is a massive help. I can’t wait for the next installment!

    0
  27. 53

    Very interesting – thanks

    0
  28. 54

    Great summary of a lot of the techniques I use every day! I even learned some new stuff, so thanks for that. All in all a great read-up for beginning WordPress developers.

    0
    • 55

      Gport, thank you for your kind words! Did you take a look at the reference to adding custom fields to your custom taxonomies? That is a more advanced tutorial and it may not be new to you and your development experience. If it is new, though, its another good technique to add to your developer toolbelt.

      0
  29. 56

    Please post the next article quickly… I am so eagerly waiting.. nice post :)

    0
  30. 57

    Mariusz Slonina

    June 3, 2011 4:49 am

    This is much much easier in Drupal7 than in WordPress (no php coding for custom fields, custom content types, custom taxonomies, storage or whatever).

    0
  31. 58

    Thanks for the tutorial – it’s been a big help. I’m brand new to WordPress and am having a little trouble viewing my “resource” post. I can view it at ?resource=vimeo-video, but it doesn’t show up as a post in my blog. I’m most likely missing something but shouldn’t it show up as a normal post when published as a resource? Thanks!

    0
    • 59

      Hey Joshua! Thank you for stopping by. By default, your “resource” post will not show up in the index of blog posts. You could modify the query to return your custom posts as well. Take a look at the reference to query_posts on the WordPress Codex. Read through that and a bit down the page it includes an example to modify the query to show multiple post types.

      0
  32. 60

    Any Completed Example Code of this tutorial?

    0
    • 61

      Jauhari, I did not put together a completed code example. There will be, however, additional code samples in part 2. Considering the nature of the tutorial and the likelihood that real world implementations will vary dramatically, I thought it best to take one example on my own site and just give code samples that could be modified to fit your own project.

      0
  33. 62

    Or…you could just do it out of the box with Drupal. WordPress is great for blogs; anything more, and you’re just pushing it beyond where it was designed to go.

    0
    • 63

      Hey Scott, thanks for your comment! A few years ago, WordPress being focused on blogs was true. A lot has changed over the past few years. What I hoped to convey here is that setting up more advanced sites _is_ now something you can do out of the box and it will become increasingly more that way as WordPress grows. If Drupal is a match for a project, though, by all means run with it. If you’re familiar and comfortable with WordPress, my goal is to let folks know that they can take WordPress further.

      0
    • 64

      awesome point. this a great article on the capabilities of wordpress, and jonathan’s done a great job of laying out techniques for building a more capable wordpress cms…

      …but hey smashing, where’s the drupal love? can we get an article about 7?

      much love and appreciation.

      0
  34. 65

    Nice Article!!!

    0
  35. 66

    Nice Job Jonathan!

    0
  36. 67

    Michael Persson

    June 5, 2011 1:28 am

    Really great post… WordPress is really interesting and have great potential and is also very easy to introduce to new clients…

    0
  37. 68

    thanks so much for this detailed post! colleagues call me crazy, but seeing such detailed tuts in WP actually helps me wrap my mind around PHP – the one thing i miss in my CV.
    thanks a lot !

    0
  38. 69

    Great article Jonathan! Very comprehensive. Thanks for the opportunity to review it. Looking forward to the next part!

    0
  39. 70

    Using $post->guid for the Video URL is just plain wrong. This won’t work. Furthermore the GUID will change with the next release.

    0
    • 71

      K, thank you for your comment. Would you point out what the difficulty is? I’ve tested the code and, so far, have found it to work well. I’m always looking for the best practice, though, and any suggestions are appreciated. Also, would you reference me where I can learn about changes to the GUID?

      0
  40. 72

    Carlo Rizzante

    June 6, 2011 3:01 am

    There are some minimal inaccuracies in the codes, for instance, the Vimeo code will not work that way (confront it with the snippet Vimeo itself provide), but the article is still superb. I enjoyed reading it and following the process.

    Thanks, looking forward to the next part.
    Carlo

    0
    • 73

      Carlo, thank you for stopping by! I have tested the code and, at least in my examples, it has worked without trouble. To my knowledge, my implementation follows their recommended best practice. If you have any ideas or suggestions for improvement or a reference to a better practice I may have missed, please let me know – Thank you!

      0
  41. 74

    You should use Drupal for this.

    0
  42. 75

    Great compilation article! Rarely see so many clear WP instructions in a single article. Will be a reference from now on.

    0
  43. 76

    What would the template be for youtube embedding rather than vimeo?

    I guess it is best to have just 1 ‘video’ custom post type so would you have vimeo and youtube in the same template and then have different custom fields?

    0
  44. 77

    Hi Johnathan, the timing of your article is fantastic,

    People’s comments here have been interesting – I have been facing off drupal vs wordpress for a project just like this. I find clients prefer wordpress for ease of use, but drupal definitely has much much power.

    One of the features I’ve been looking for in the solution however is video encoding. Today I came across this -
    http://mobilevideoforwordpress.com/ which would seemingly take care of the handling of the media – with CDN integration!

    So now, I am imagining this with an upload field that passes it to the plugin. Now that would be sweet!

    So im looking forward to part two… But now I wouldn’t mind seeing part 3 :P

    0
  45. 78

    Jonathan, thanks for the detailed steps. I would like to know Why do we need custom post / pages and taxonomies, How does that make a difference. I havent made any such use yet.

    0
  46. 79

    Jonathan,

    Thanks for this tutorial. Great info, clear steps, and plenty of links to other useful plugins and resources peppered throughout. Really top notch stuff. There was a section that tripped me up, however.

    In the section entitled “Preparing the Stage — Adding New Media,” your fourth bullet point says this:

    Add one or more custom fields with a unique “key” and “value” (e.g. a key of “recording_duration” and a value of “00:02:34″).

    Being the newb that I am, I did exactly as you instructed and created the custom field with the key “recording_duration”. Later, however, in the section entitled “Creating a Custom Post Type Template” you give us the code for the single-resource.php template file wherein you have this code …

    $recording_date = get_post_meta( $post->ID, ‘recording_date’, true );
    $recording_length = get_post_meta( $post->ID, ‘recording_length’, true );

    It took me a few minutes to realize that my custom field with the key of “recording_duration” was never going to line up with “recording_length”. LOL.

    I changed my key in my test resource post to coincide with the code in single-resource.php and all was good. I also added a custom field with the key for recording_date.

    So, if I may be so bold, may I suggest that you modify the fourth bullet point in the “Preparing the Stage” section to be a “do this exactly” step and not a mere suggestion because, like I say, we newbs tend to blindly do what is asked of us, then when the code is different later, well, you know, newb brain chaos ensues.

    Last thing—and I may be a bit premature with this since I haven’t finished the entire tutorial—but I can’t seem to make the link to my test resource post work with anything but the default (i.e., ugly) permalink structure.

    Whenever I change to one of the pretty permalink options in the site settings, my test resource article itself wants to use a permalink of http://www.mydomain.com/resource/resource-item-title, but it still gives me a page not found error. My .htaccess file is in place and working with other test postings and pages, so I’m befuddled as to why it won’t work with my custom post type. I’m sure it’s an issue that can be resolved using a custom permalink and the proper structure tags, but that’s beyond my ken at the moment. Any suggestions?

    0
    • 80

      Excellent point, I too was struggling to get the recording date and duration to show up, I didn’t realise they haad to be named the same as in the code. A small niggle in an otherwise fantastic tutorial.

      0
  47. 81

    great explanation!!! thank you……..looking forward to part two..

    0
  48. 82

    I just learned an assload (that’s alot, by the way!) about WordPress through this tutorial. Now, I need to figure out how to turn these bad boys into plugins! Hands down, the most helpful post I’ve read on Smashing Mag (and I’ve been reading for years).

    0
  49. 83

    Igors Brezinskis

    June 19, 2011 2:03 am

    Thanks nice post! I am intrested if you add custom fields in function.php and then update wordpress Will it erase custom fields or they stay forever? Or is there any solution to protect function.php form update?

    0
  50. 84

    This is a great post, super informative and I really appreciate it.

    I have a little hiccup though and I can’t seem to find an answer. If I take what you’re doing with “topics” and I apply it, the permalinks don’t show the sub topics.

    Example:
    If in my custom taxonomy I add a category called clothes this is the permalink I get:
    /product/product-name

    It’d be great if it were: /product/clothes/product-name

    How does that work? Thanks!!!!

    0
  51. 85

    Great article! Quick question though – I would like to create more than one post types, but when I do I receive this message:

    “Fatal error: Cannot redeclare register_rc()”

    Is there a way around this?

    Thank you.

    0
    • 86

      Kyle, what you’ll need to do is rename the function from “register_rc” to another function name of your choice – for example, “register_other_posttype”.

      0
  52. 87

    Fantastic article! Have it bookmarked, saved, referenced, linked, printed, pinned….you name it! :D

    0
  53. 88

    I noticed that everything worked for me except that my sidebar is gone. Any ideas why?

    0
  54. 89

    What happened to Part 2 of this article, and were any other sections published?

    0
  55. 91

    Thanks. Great tutorial. Useful for me :)

    0
  56. 92

    Where is Part 2? I keep getting a looping redirect when I click through from Google Reader and it doesn’t come up in site search either.

    :’(

    0
  57. 94

    After creating a custom post type and making a post of that type, my .current_page_parent class is on my blog list item parent, not my custom post type list item parent.

    So when reading a custom post type, the nav style shows that you’re in the blog parent and not the custom post type parent.

    How do I fix this?

    0
  58. 95

    Jean Gerard Bousiquot

    March 3, 2013 6:57 pm

    Hello there ! I’m just done reading this amazing part. Now I’m putting all of this in practice for my media website. Thanks for sharing your knowledge !

    - Regards, JGB

    0
  59. 96

    Waldir Informatica

    April 22, 2013 1:59 pm

    May I just say what a comfort to find an individual who actually understands what they’re talking about over the internet. You actually understand how to bring a problem to light and make it important. More and more people ought to read this and understand this side of your story. I can’t believe you are not more popular since you surely possess the gift.

    0
  60. 97

    Is it possible to add an audio player instead of video player?
    I’d like to turn this into an Audio CPT…

    0

↑ Back to top