<?xml version="1.0" encoding="UTF-8"?>
 <rdf:RDF xmlns="http://purl.org/rss/1.0/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://web.resource.org/cc/" xmlns:syn="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/">
  <channel rdf:about="http://pinboard.in">
    <title>Pinboard (alexhansford)</title>
    <link>https://pinboard.in/u:alexhansford/public/</link>
    <description>recent bookmarks from alexhansford</description>
    <items>
      <rdf:Seq>	<rdf:li rdf:resource="http://www.smashingmagazine.com/2011/10/07/wordpress-essentials-the-definitive-guide-to-wordpress-hooks/"/>
	<rdf:li rdf:resource="http://www.smashingmagazine.com/2011/10/04/how-to-create-custom-post-meta-boxes-in-wordpress/"/>
	<rdf:li rdf:resource="http://andwat.edublogs.org/"/>
	<rdf:li rdf:resource="http://www.cre8d-design.com/blog/2007/01/01/useful-resources-for-creating-a-wordpress-theme/"/>
	<rdf:li rdf:resource="http://mashable.com/2007/08/16/wordpress-god300-tools-for-running-your-wordpress-blog/#more-8593"/>
	<rdf:li rdf:resource="http://silentbits.com/?p=385"/>
	<rdf:li rdf:resource="http://lab.christianmontoya.com/css-dates/"/>
	<rdf:li rdf:resource="http://www.smashingmagazine.com/2011/06/02/how-to-build-a-media-site-on-wordpress-part-1/"/>
	<rdf:li rdf:resource="http://coderseye.com/2006/multi-blogging-for-wordpress-update.html"/>
      </rdf:Seq>
    </items>
  </channel><item rdf:about="http://www.smashingmagazine.com/2011/10/07/wordpress-essentials-the-definitive-guide-to-wordpress-hooks/">
    <title>WordPress Essentials: The Definitive Guide To WordPress Hooks</title>
    <dc:date>2011-10-07T22:48:46+00:00</dc:date>
    <link>http://www.smashingmagazine.com/2011/10/07/wordpress-essentials-the-definitive-guide-to-wordpress-hooks/</link>
    <dc:creator>alexhansford</dc:creator><description><![CDATA[



        
        
          
        
         
        
          
        
         
        
          
        
      



If you’re into WordPress development, you can’t ignore hooks for long before you have to delve into them head on. Modifying WordPress core files is a big no-no, so whenever you want to change existing functionality or create new functionality, you will have to turn to hooks.



In this article, I would like to dispel some of the confusion around hooks, because not only are they the way to code in WordPress, but they also teach us a great design pattern for development in general. Explaining this in depth will take a bit of time, but bear with me: by the end, you’ll be able to jumble hooks around like a pro.

Why Hooks Exist
I think the most important step in grasping hooks is to understand the need for them. Let’s create a version of a WordPress function that already exists, and then evolve it a bit using the “hooks mindset.”


   function get_excerpt($text, $length = 150) {
      $excerpt = substr($text,$length)
      return $excerpt;
   }

This function takes two parameters: a string and the length at which we want to cut it. What happens if the user wants a 200-character excerpt instead of a 150-character one? They just modify the parameter when they use the function. No problem there.

If you use this function a lot, you will notice that the parameter for the text is usually the post’s content, and that you usually use 200 characters instead of the default 150. Wouldn’t it be nice if you could set up new defaults, so that you didn’t have to add the same parameters over and over again? Also, what happens if you want to add some more custom text to the end of the excerpt?

These are the kinds of problems that hooks solve. Let’s take a quick look at how.


   function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length", $length);

      $excerpt = substr($text,$length)
      return $excerpt;
   }

As you can see, the default excerpt length is still 150, but we’ve also applied some filters to it. A filter allows you to write a function that modifies the value of something — in this case, the excerpt’s length. The name (or tag) of this filter is excerpt_length, and if no functions are attached to it, then its value will remain 150. Let’s see how we can now use this to modify the default value.


   function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length");

      $excerpt = substr($text,$length)
      return $excerpt;
   }

   function modify_excerpt_length() {
      return 200;
   }

   add_filter("excerpt_length", "modify_excerpt_length");

First, we have defined a function that does nothing but return a number. At this point, nothing is using the function, so let’s tell WordPress that we want to hook this into the excerpt_length filter.

We’ve successfully changed the default excerpt length in WordPress, without touching the original function and without even having to write a custom excerpt function. This will be extremely useful, because if you always want excerpts that are 200 characters long, just add this as a filter and then you won’t have to specify it every time.

Suppose you want to tack on some more text, like “Read on,” to the end of the excerpt. We could modify our original function to work with a hook and then tie a function to that hook, like so:


   function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length");

      $excerpt = substr($text,$length)
      return apply_filters("excerpt_content", $excerpt);
   }

   function modify_excerpt_content($excerpt) {
      return $excerpt . "Read on…";
   }
   add_filter("excerpt_content", "modify_excerpt_content");

This hook is placed at the end of the function and allows us to modify its end result. This time, we’ve also passed the output that the function would normally produce as a parameter to our hook. The function that we tie to this hook will receive this parameter.

All we are doing in our function is taking the original contents of $excerpt and appending our “Read on” text to the end. But if we choose, we could also return the text “Click the title to read this article,” which would replace the whole excerpt.

While our example is a bit redundant, since WordPress already has a better function, hopefully you’ve gotten to grips with the thinking behind hooks. Let’s look more in depth at what goes on with filters, actions, priorities, arguments and the other yummy options available.

Filters And Actions
Filters and actions are two types of hooks. As you saw in the previous section, a filter modifies the value of something. An action, rather than modifying something, calls another function to run beside it.

A commonly used action hook is wp_head. Let’s see how this works. You may have noticed a function at the bottom of your website’s head section named wp_head(). Diving into the code of this function, you can see that it contains a call to do_action(). This is similar to apply_filters(); it means to run all of the functions that are tied to the wp_head tag.

Let’s put a copyright meta tag on top of each post’s page to test how this works.


   add_action("wp_head", "my_copyright_meta");

   function my_copyright_meta() {
      if(is_singular()){
         echo "";
      }
   }

The Workflow Of Using Hooks
While hooks are better documented nowadays, they have been neglected a bit until recently, understandably so. You can find some good pointers in the Codex, but the best thing to use is Adam Brown’s hook reference, and/or look at the source code.

Say you want to add functionality to your blog that notifies authors when their work is published. To do this, you would need to do something when a post is published. So, let’s try to find a hook related to publishing.

Can we tell whether we need an action or a filter? Sure we can! When a post is published, do we want to modify its data or do a completely separate action? The answer is the latter, so we’ll need an action. Let’s go to the action reference on Adam Brown’s website, and search for “Publish.”

The first thing you’ll find is app_publish_post. Sounds good; let’s click on it. The details page doesn’t give us a lot of info (sometimes it does), so click on the “View hook in source” link next to your version of WordPress (preferably the most recent version) in the table. This website shows only a snippet of the file, and unfortunately the beginning of the documentation is cut off, so it’s difficult to tell if this is what we need. Click on “View complete file in SVN” to go to the complete file so that we can search for our hook.

In the file I am viewing, the hook can be found in the _publish_post_hook() function, which — according to the documentation above it — is a “hook to schedule pings and enclosures when a post is published,” so this is not really what we need.

With some more research in the action list, you’ll find the publish_post hook, and this is what we need. The first thing to do is write the function that sends your email. This function will receive the post’s ID as an argument, so you can use that to pull some information into the email. The second task is to hook this function into the action. Look at the finished code below for the details.


   function authorNotification($post_id) {
      global $wpdb;
      $post = get_post($post_id);
      $author = get_userdata($post->post_author);

      $message = "
         Hi ".$author->display_name.",
         Your post, ".$post->post_title." has just been published. Well done!
      ";
      wp_mail($author->user_email, "Your article is online", $message);
   }
   add_action('publish_post', 'authorNotification');

Notice that the function we wrote is usable in its own right. It has a very specific function, but it isn’t only usable together with hooks; you could use it in your code any time. In case you’re wondering, wp_mail() is an awesome mailer function — have a look at the WordPress Codex for more information.

This process might seem a bit complicated at first, and, to be totally honest, it does require browsing a bit of documentation and source code at first, but as you become more comfortable with this system, your time spent researching what to use and when to use it will be reduced to nearly nothing.

Priorities
The third parameter when adding your actions and filters is the priority. This basically designates the order in which attached hooks should run. We haven’t covered this so far, but attaching multiple functions to a hook is, of course, possible. If you want an email to be sent to an author when their post is published and to also automatically tweet the post, these would be written in two separate functions, each tied to the same tag (publish_post).

Priorities designate which hooked function should run first. The default value is 10, but this can be changed as needed. Priorities usually don’t make a huge difference, though. Whether the email is sent to the author before the article is tweeted or vice versa won’t make a huge difference.

In rarer cases, assigning a priority could be important. You might want to overwrite the actions of other plugins (be careful, in this case), or you might want to enforce a specific order. I recently had to overwrite functionality when I was asked to optimize a website. The website had three to four plugins, with about nine JavaScript files in total. Instead of disabling these plugins, I made my own plugin that overwrote some of the JavaScript-outputting functionality of those plugins. My plugin then added the minified JavaScript code in one file. This way, if my plugin was deactivated, all of the other plugins would work as expected.

Specifying Arguments
The fourth argument when adding filters and actions specifies how many arguments the hooked function takes. This is usually dictated by the hook itself, and you will need to look at the source to find this information.

As you know from before, your functions are run when they are called by apply_filters() or do_action(). These functions will have the tag as their first argument (i.e. the name of the hook you are plugging into) and then passed arguments as subsequent arguments.

For example, the filter default_excerpt receives two parameters, as seen in includes/post.php.


   $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );

The arguments are well named — $post_excerpt and $post — so it’s easy to guess that the first is the excerpt text and the second is the post’s object. If you are unsure, it is usually easiest either to look further up in the source or to output them using a test function (make sure you aren’t in a production environment).


   function my_filter_test($post_excerpt, $post) {
      echo "<pre>";
         print_r($post_excerpt);
         print_r($post);
      echo "</pre>";
   }
   add_filter("default_excerpt", "my_filter_test");

Variable Hook Names
Remember when we looked at the publish_post action? In fact, this is not used anymore; it was renamed in version 2.3 to {$new_status}_{$post->post_type}. With the advent of custom post types, it was important to make the system flexible enough for them. This new hook now takes an arbitrary status and post type (they must exist for it to work, obviously).

As a result, publish_post is the correct tag to use, but in reality, you will be using {$new_status}_{$post->post_type}. A few of these are around; the naming usually suggests what you will need to name the action.

Who Is Hooked On Who?
To find out which function hooks into what, you can use the neat script below, courtesy of WP Recipes. Use this function without arguments to get a massive list of everything, or add a tag to get functions that are hooked to that one tag. This is a great one to keep in your debugging tool belt!


function list_hooked_functions($tag=false){
 global $wp_filter;
 if ($tag) {
  $hook[$tag]=$wp_filter[$tag];
  if (!is_array($hook[$tag])) {
  trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
  return;
  }
 }
 else {
  $hook=$wp_filter;
  ksort($hook);
 }
 echo '<pre>';
 foreach($hook as $tag => $priority){
  echo "<br /><strong>$tag</strong><br />";
  ksort($priority);
  foreach($priority as $priority => $function){
  echo $priority;
  foreach($function as $name => $properties) echo "\t$name<br />";
  }
 }
 echo '</pre>';
 return;
}

Creating Your Own Hooks
A ton of hooks are built into WordPress, but nothing is stopping you from creating your own using the functions we’ve looked at so far. This may be beneficial if you are building a complex plugin intended for wide release; it will make your and other developers’ jobs a lot easier!

In the example below, I have assumed we are building functionality for users to post short blurbs on your website’s wall. We’ll write a function to check for profanity and hook it to the function that adds the blurbs to the wall.

Look at the full code below. The explanation ensues.


   function post_blurb($user_id, $text) {

      $text = apply_filters("blurb_text", $text);

      if(!empty($text)) {
         $wpdb->insert('my_wall', array("user_id" => $user_id, "date" => date("Y-m-d H:i:s"), "text" => $text), array("%d", %s", "%s"));
      }
   }

   function profanity_filter($text) {
      $text_elements = explode(" ", $text);
      $profanity = array("badword", "naughtyword", "inappropriatelanguage");

      if(array_intersect($profanity, $text_elements)) {
         return false;
      }
      else {
         return $text;
      }
   }

   add_filter("blurb_text", "profanity_filter");

The first thing in the code is the designation of the function that adds the blurb. Notice that I included the apply_filters() function, which we will use to add our profanity check.

Next up is our profanity-checking function. This checks the text as its argument against an array of known naughty words. By using array_intersect(), we look for array elements that are in both arrays — these would be the profane words. If there are any, then return false; otherwise, return the original text.

The last part actually hooks this function into our blurb-adding script.

Now other developers can hook their own functions into our script. They could build a spam filter or a better profanity filter. All they would need to do is hook it in.

Mixing And Matching
The beauty of this system is that it uses functions for everything. If you want, you can use the same profanity filter for other purposes, even outside of WordPress, because it is just a simple function. Already have a profanity-filter function? Copy and paste it in; all you’ll need to do is add the one line that actually hooks it in. This makes functions easily reusable in various situations, giving you more flexibility and saving you some time as well.

That’s All
Hopefully, you now fully understand how the hooks system works in WordPress. It contains an important pattern that many of us could use even outside of WordPress.

This is one aspect of WordPress that does take some time getting used to if you’re coming to it without any previous knowledge. The biggest problem is usually that people get lost in all of the filters available or in finding their arguments and so on, but with some patience this can be overcome easily. Just start using them, and you’ll be a master in no time!

(al)


© Daniel Pataki for Smashing Magazine, 2011.
]]></description>
<dc:subject>Coding WordPress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:bb23989dbc23/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Coding"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:WordPress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://www.smashingmagazine.com/2011/10/04/how-to-create-custom-post-meta-boxes-in-wordpress/">
    <title>How To Create Custom Post Meta Boxes In WordPress</title>
    <dc:date>2011-10-04T17:33:51+00:00</dc:date>
    <link>http://www.smashingmagazine.com/2011/10/04/how-to-create-custom-post-meta-boxes-in-wordpress/</link>
    <dc:creator>alexhansford</dc:creator><description><![CDATA[



        
        
          
        
         
        
          
        
         
        
          
        
      



What seems like one of the most complicated bits of functionality in WordPress is adding meta boxes to the post editing screen.  This complexity only grows as more and more tutorials are written on the process with weird loops and arrays.  Even meta box “frameworks” have been developed.  I’ll let you in on a little secret though: it’s not that complicated.



Creating custom meta boxes is extremely simple, at least it is once you’ve created your first one using the tools baked into WordPress’ core code.  In this tutorial, I’ll walk you through everything you need to know about meta boxes:


Creating meta boxes.
Using meta boxes with any post type.
Handling data validation.
Saving custom meta data.
Retrieving custom meta data on the front end.

Note:  When I use the term “post” throughout this tutorial, I’m referring to a post of any post type, not just the default blog post type bundled with WordPress.

What is a post meta box?
A post meta box is a draggable box shown on the post editing screen.  Its purpose is to allow the user to select or enter information in addition to the main post content.  This information should be related to the post in some way.

Generally, two types of data is entered into meta boxes:


Metadata (i.e. custom fields),
Taxonomy terms.

Of course, there are other possible uses, but those two are the most common.  For the purposes of this tutorial, you’ll be learning how to develop meta boxes that handle custom post metadata.

What is post metadata?
Post metadata is data that’s saved in the wp_postmeta table in the database.  Each entry is saved as four fields in this table:


meta_id:  A unique ID for this specific metadata.
post_id:  The post ID this metadata is attached to.
meta_key:  A key used to identify the data (you’ll work with this often).
meta_value:  The value of the metadata.

In the following screenshot, you can see how this looks in the database.



When you get right down to it, metadata is just key/value pairs saved for a specific post.  This allows you to add all sorts of custom data to your posts.  It is especially useful when you’re developing custom post types.

The only limit is your imagination.

Note:  One thing to keep in mind is that a single meta key can have multiple meta values.  This isn’t a common use, but it can be extremely powerful.

Working with post metadata
By now, you’re probably itching to build some custom meta boxes.  However, to understand how custom meta boxes are useful, you must understand how to add, update, delete, and get post metadata.

I could write a book on the various ways to use metadata, but that’s not the main purpose of this tutorial.  You can use the following links to learn how the post meta functions work in WordPress if you’re unfamiliar with them.


add_post_meta():  Adds post metadata.
update_post_meta():  Updates post metadata.
delete_post_meta():  Deletes post metadata.
get_post_meta():  Retrieves post metadata.

The remainder of this tutorial assumes that you’re at least familiar with how these functions work.

The setup
Before building meta boxes, you must have some ideas about what type of metadata you want to use.  This tutorial will focus on building a meta box that saves a custom post CSS class, which can be used to style posts.

I’ll start you off by teaching you to develop custom code that does a few extremely simple things:


Adds an input box for you to add a custom post class (the meta box).
Saves the post class for the smashing_post_class meta key.
Filters the post_class hook to add your custom post class.

You can do much more complex things with meta boxes, but you need to learn the basics first.

All of the PHP code in the following sections goes into either your custom plugin file or your theme’s functions.php file.

Building a custom post meta box
Now that you know what you’re building, it’s time to start diving into some code.  The first two code snippets in this section of the tutorial are mostly about setting everything up for the meta box functionality.

Since you only want your post meta box to appear on the post editor screen in the admin, you’ll use the load-post.php and load-post-new.php hooks to initialize your meta box code.

/* Fire our meta box setup function on the post editor screen. */
add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );
Most WordPress developers should be familiar with how hooks work, so this should not be anything new to you.  The above code tells WordPress that you want to fire the smashing_post_meta_boxes_setup function on the post editor screen.  The next step is to create this function.

The following code snippet will add your meta box creation function to the add_meta_boxes hook.  WordPress provides this hook to add meta boxes.

/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {

/* Add meta boxes on the 'add_meta_boxes' hook. */
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
}
Now, you can get into the fun stuff.

In the above code snippet, you added the smashing_add_post_meta_boxes() function to the add_meta_boxes hook.  This function’s purpose should be to add post meta boxes.  

In the next example, you’ll create a single meta box using the add_meta_box() WordPress function.  However, you can add as many meta boxes as you like at this point when developing your own projects.

Before proceeding, let’s look at the add_meta_box() function:


add_meta_box( $id, $title, $callback, $page, $context = 'advanced', $priority = 'default', $callback_args = null );


$id:  This is a unique ID assigned to your meta box.  It should have a unique prefix and be valid HTML.
$title:  The title of the meta box.  Remember to internationalize this for translators.
$callback:  The callback function that displays the output of your meta box.
$page:  The admin page to display the meta box on.  In our case, this would be the name of the post type (post, page, or a custom post type).
$context:  Where on the page the meta box should be shown.  The available options are normal, advanced, and side.
$priority:  How high/low the meta box should be prioritized.  The available options are default, core, high, and low.
$callback_args:  An array of custom arguments you can pass to your $callback function as the second parameter.

The following code will add the post class meta box to the post editor screen.

/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {

add_meta_box(
'smashing-post-class',// Unique ID
esc_html__( 'Post Class', 'example' ),// Title
'smashing_post_class_meta_box',// Callback function
'post',// Admin page (or post type)
'side',// Context
'default'// Priority
);
}
You still need to display the meta box’s HTML though.  That’s where the smashing_post_class_meta_box() function comes in ($callback parameter from above).

/* Display the post meta box. */
function smashing_post_class_meta_box( $object, $box ) { ?>

<?php wp_nonce_field( basename( __FILE__ ), 'smashing_post_class_nonce' ); ?>

<p>
<label for="smashing-post-class"><?php _e( "Add a custom CSS class, which will be applied to WordPress' post class.", 'example' ); ?></label>
<br />
<input class="widefat" type="text" name="smashing-post-class" id="smashing-post-class" value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>" size="30" />
</p>
<?php }
What the above function does is display the HTML output for your meta box.  It displays a hidden nonce input (you can read more about nonces on the WordPress Codex).  It then displays an input element for adding a custom post class as well as output the custom class if one has been input.

At this point, you should have a nice-looking meta box on your post editing screen.  It should look like the following screenshot.



The meta box doesn’t actually do anything yet though.  For example, it won’t save your custom post class.  That’s what the next section of this tutorial is about.

Saving the meta box data
Now that you’ve learned how to create a meta box, it’s time to learn how to save post metadata.

Remember that smashing_post_meta_boxes_setup() function you created earlier?  You need to modify that a bit.  You’ll want to add the following code to it.

/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
So, that function will actually look like this:

/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {

/* Add meta boxes on the 'add_meta_boxes' hook. */
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );

/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
}
The new code you’re adding tells WordPress that you want to run a custom function on the save_post hook.  This function will save, update, or delete your custom post meta.

When saving post meta, your function needs to run through a number of processes:


Verify the nonce set in the meta box function.
Check that the current user has permission to edit the post.
Grab the posted input value from $_POST.
Decide whether the meta should be added, updated, or deleted based on the posted value and the old value.

I’ve left the following function somewhat generic so that you’ll have a little flexibility when developing your own meta boxes.  It is the final snippet of code that you’ll need to save the metadata for your custom post class meta box.

/* Save the meta box's post metadata. */
function smashing_save_post_class_meta( $post_id, $post ) {

/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_post_class_nonce'] ) || !wp_verify_nonce( $_POST['smashing_post_class_nonce'], basename( __FILE__ ) ) )
return $post_id;

/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );

/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;

/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-post-class'] ) ? sanitize_html_class( $_POST['smashing-post-class'] ) : '' );

/* Get the meta key. */
$meta_key = 'smashing_post_class';

/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );

/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, $meta_key, $new_meta_value, true );

/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $meta_key, $new_meta_value );

/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $meta_key, $meta_value );
}
At this point, you can save, update, or delete the data in the “Post Class” meta box you created from the post editor screen.

Using the metadata from meta boxes
So you have a custom post meta box that works, but you still need to do something with the metadata that it saves.  That’s the point of creating meta boxes.  What to do with your metadata will change from project to project, so this is not something I can answer for you.  However, you will learn how to use the metadata from the meta box you’ve created.

Since you’ve been building a meta box that allows a user to input a custom post class, you’ll need to filter WordPress’ post_class hook so that the custom class appears alongside the other post classes.

Remember that get_post_meta() function from much earlier in the tutorial?  You’ll need that too.

The following code adds the custom post class (if one is given) from your custom meta box.

/* Filter the post class hook with our custom post class function. */
add_filter( 'post_class', 'smashing_post_class' );

function smashing_post_class( $classes ) {

/* Get the current post ID. */
$post_id = get_the_ID();

/* If we have a post ID, proceed. */
if ( !empty( $post_id ) ) {

/* Get the custom post class. */
$post_class = get_post_meta( $post_id, 'smashing_post_class', true );

/* If a post class was input, sanitize it and add it to the post class array. */
if ( !empty( $post_class ) )
$classes[] = sanitize_html_class( $post_class );
}

return $classes;
}
If you look at the source code of the page where this post is shown on the front end of the site, you’ll see something like the following screenshot.



Pretty cool, right? You can use this custom class to style posts however you want in your theme’s stylesheet.

Security
One thing you should keep in mind when saving data is security.  Security is a lengthy topic and is outside the scope of this article.  However, I thought it best to at least remind you to keep security in mind.

You’ve already been given a link explaining nonces earlier in this tutorial.  The other resource I want to provide you with is the WordPress Codex guide on data validation.  This documentation will be your best friend when learning how to save post metadata and will provide you with the tools you’ll need for keeping your plugins/themes secure.

Bonus points to anyone who can name all of the security measures used throughout this tutorial.

Create a custom meta box
Once you’ve copied, pasted, and tested the bits of pieces of code from this tutorial, I encourage you to try out something even more complex.  If you really want to see how powerful meta boxes and post metadata can be, try doing something with a single meta key and multiple meta values for that key (it’s challenging).

I hope you’ve enjoyed the tutorial. Feel free to post questions about creating meta boxes in the comments.

(al)


© Justin Tadlock for Smashing Magazine, 2011.
]]></description>
<dc:subject>WordPress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:86ad42024873/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:WordPress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://andwat.edublogs.org/">
    <title>How Do You MU?</title>
    <dc:date>2011-06-08T17:07:14+00:00</dc:date>
    <link>http://andwat.edublogs.org/</link>
    <dc:creator>alexhansford</dc:creator><dc:subject>Bookmarks delicious-export wordpress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:0ec19f9be0eb/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Bookmarks"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:delicious-export"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:wordpress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://www.cre8d-design.com/blog/2007/01/01/useful-resources-for-creating-a-wordpress-theme/">
    <title>Useful resources for creating a Wordpress theme | cre8d design: blog design, Wordpress themes, Drupal, Web 2.0</title>
    <dc:date>2011-06-08T17:04:23+00:00</dc:date>
    <link>http://www.cre8d-design.com/blog/2007/01/01/useful-resources-for-creating-a-wordpress-theme/</link>
    <dc:creator>alexhansford</dc:creator><dc:subject>Bookmarks blog delicious-export design howto reference tips webdesign wordpress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:d4939803c46d/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Bookmarks"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:blog"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:delicious-export"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:design"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:howto"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:reference"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:tips"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:webdesign"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:wordpress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://mashable.com/2007/08/16/wordpress-god300-tools-for-running-your-wordpress-blog/#more-8593">
    <title>WORDPRESS GOD: 300+ Tools for Running Your WordPress Blog</title>
    <dc:date>2011-06-08T16:18:01+00:00</dc:date>
    <link>http://mashable.com/2007/08/16/wordpress-god300-tools-for-running-your-wordpress-blog/#more-8593</link>
    <dc:creator>alexhansford</dc:creator><dc:subject>Bookmarks delicious-export tools wordpress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:18149f3638a4/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Bookmarks"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:delicious-export"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:tools"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:wordpress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://silentbits.com/?p=385">
    <title>Top 20 Blog Designs</title>
    <dc:date>2011-06-08T16:07:50+00:00</dc:date>
    <link>http://silentbits.com/?p=385</link>
    <dc:creator>alexhansford</dc:creator><dc:subject>Bookmarks delicious-export design inspiration webdesign wordpress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:590b460e3ac2/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Bookmarks"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:delicious-export"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:design"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:inspiration"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:webdesign"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:wordpress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://lab.christianmontoya.com/css-dates/">
    <title>Hot Dates with CSS by Christian Montoya, christianmontoya.com</title>
    <dc:date>2011-06-08T16:02:01+00:00</dc:date>
    <link>http://lab.christianmontoya.com/css-dates/</link>
    <dc:creator>alexhansford</dc:creator><dc:subject>Bookmarks css delicious-export design howto tutorial webdesign wordpress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:7fda3e3b2a44/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Bookmarks"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:css"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:delicious-export"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:design"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:howto"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:tutorial"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:webdesign"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:wordpress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://www.smashingmagazine.com/2011/06/02/how-to-build-a-media-site-on-wordpress-part-1/">
    <title>How To Build A Media Site On WordPress (Part 1)</title>
    <dc:date>2011-06-02T15:04:15+00:00</dc:date>
    <link>http://www.smashingmagazine.com/2011/06/02/how-to-build-a-media-site-on-wordpress-part-1/</link>
    <dc:creator>alexhansford</dc:creator><description><![CDATA[



      
        
    



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.


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:


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:

 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:

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:

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:

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:


Download the player from the Longtail Video website.
Create a folder within your theme to hold the player files – In this case, I’ve named the folder “jw”.
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:

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.

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. Stay tuned!

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. 



© Jonathan Wold for Smashing Magazine, 2011. |
Permalink | 
Post a comment | 
Smashing Shop |
Smashing Network |
About Us


Post tags: coding, WordPress

]]></description>
<dc:subject>Coding WordPress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:30df6f32df23/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Coding"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:WordPress"/>
</rdf:Bag></taxo:topics>
</item>
<item rdf:about="http://coderseye.com/2006/multi-blogging-for-wordpress-update.html">
    <title>Multi-blogging for Wordpress update</title>
    <dc:date>2007-07-11T23:31:08+00:00</dc:date>
    <link>http://coderseye.com/2006/multi-blogging-for-wordpress-update.html</link>
    <dc:creator>alexhansford</dc:creator><dc:subject>Bookmarks delicious-export howto wordpress</dc:subject>
<dc:identifier>https://pinboard.in/u:alexhansford/b:18a6d06e449d/</dc:identifier>
<taxo:topics><rdf:Bag>	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:Bookmarks"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:delicious-export"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:howto"/>
	<rdf:li rdf:resource="https://pinboard.in/u:alexhansford/t:wordpress"/>
</rdf:Bag></taxo:topics>
</item>
</rdf:RDF>