WordPress Essentials: The Definitive Guide To WordPress Hooks
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 u[…]
Coding
WordPress
from google
october 2011 by alexhansford
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 u[…]
october 2011 by alexhansford
How To Create Custom Post Meta Boxes In WordPress
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[…]
WordPress
from google
october 2011 by alexhansford
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[…]
october 2011 by alexhansford
How To Build A Media Site On WordPress (Part 1)
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[…]
Coding
WordPress
from google
june 2011 by alexhansford
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[…]
june 2011 by alexhansford
Copy this bookmark: