How to Use New WordPress 3.0 Features That Will Save You Tons of Time
Well there is a ton of buzz about WordPress 3.0, but I realized that not to much documentation is out yet about how to use the fun and easy stuff, so here goes. But first, some disclaimers so I don't get yelled at by.
- Even though the attached file is in WordPress plugin format, I did not release this as a plugin.
- I did not include stuff like validation, sanitation, etc. on user input fields, only because I wanted to show the new features and save on the time to write this. Always validate and sanitize your inputs.
- As with everything, there is usually more than 1 way to go about it. The methods I list below WORK FOR ME in a custom blog I am about to launch and follow the WordPress functions documentation. Don't flame me if you don't like the way I did it, please stay constructive.
- I did not include code comment on the source code, since, I more than did the job here in this article.
- I did not add any localization.
- I apologize in advance if the source highlighter looks funky, please download the zip file for a nicely formatted PHP code file
So on we go..............
So I am breaking this up into the following logical steps of using these features, and of course, you can download the complete source below. To make this flow easy, let's talk English for a minute. Imagine the scenario: we have a WordPress 3.0 self hosted installation and we want to have HTML email templates that we can add, edit, and display using the admin and the front public pages. For the sake of the techies, these templates get read by a custom function, the scope outside of this article. So how do we do it? It's EASY!!!!!
Step by step:
- Create a plugin that will do all the stuff we need
- Create a container to hold our HTML email templates
- We need the ability to attach specific custom data to the templates
- We need to assign taxonomies to the templates (aka assign some type of categorization)
- We need to save our custom fields that are in our custom meta boxes
- We need the ability to display them on the public user pages
Before we get into it, I prefer to do this stuff in the plugin system. You can certainly do it in your theme functions.php file, if you want to. Also, I like the PHP class structure instead of a bunch of plugins, which is how I wrote this. Again, if you want to use simple functions, go for it.
Step 1: Create the plugin file. So, I just created a folder called demo under /wp-content/plugins, and created a PHP file called demo.php inside it. Then I start building the class, so here's how it looks.
<?php
/*
Plugin Name: WP 3.0 Advanced Features Demo
Plugin URI: http://passavanti.name/blogarticle
Description: This is a demo of new WordPress 3.0 features, like custom post types, custom taxonomies, easier options save settings, and more.
Version: 1.0
Author: Brian
Author URI: http://passavanti.name
*/
class wp30demo {
Step 2: Create a Custom Post Type which will also give us automatically the left hand menu page and navigation in admin. See the snippet below and the WordPress codex link to register_post_type().
public function createCustomPostType()
{
// labels gives us the options to label headings, pages, etc. to match what we are adding
$labels = array('add_new_item'=>'Add New Template',
'edit_item'=>'Edit Template',
'new_item'=>'New Template',
'view_item'=>'View Template',
'search_items'=>'Search Template'
);
register_post_type('mailtemplate', array( // the mailtemplate is the ID, the glue of all of this
'label' => 'Templates',
'labels' => $labels,
'singular_label' => 'Template',
'public' => true, // so that it can be displayed
'show_ui' => true, // UI in admin panel
'_builtin' => false, // It's a custom post type, not built in!
'_edit_link' => 'post.php?post=%d',
'capability_type' => 'page', // or 'post'
'hierarchical' => false,
'register_meta_box_cb' => array(&$this, 'registerMetaBoxes'), // to add your own meta boxes, register the callback
'rewrite' => array('slug' => 'template'), // for the front side URL
'supports' => array('title','editor') // remove standard meta boxes
));
}
Step 3: Attaching custom data via Custom Taxonomies and Custom Meta Boxes is just as easy. Reference WordPress codex for add_meta_box().
public function registerMetaBoxes() // this the callback from above
{
//add_meta_box('uniqueName','description','function to create','post type id','display on side or in middle','priority');
add_meta_box( 'emailtemplateMetaBox1', 'Some Meta Info', array(&$this, 'simpleMetaBox'), 'mailtemplate', 'side', 'high' );
add_meta_box( 'emailtemplateMetaBox2', 'Text Version', array(&$this, 'bigMetaBox'), 'mailtemplate', 'normal', 'high' );
}
public function simpleMetaBox() // here we draw a simple box with a couple form fields (Custom Fields)
{
global $post;
$custom = get_post_custom($post->ID);
$emailCheckBox1 = $custom['emailCheckBox1'][0];
$emailTextBox = $custom['emailTextBox'][0];
// you only need once nonce per form, so we can skip that on this box
?>
<input type="checkbox" id="emailCheckBox1" name="emailCheckBox1" value="1" <?php echo ($emailCheckBox1 == '1') ? 'checked="checked"':''; ?>/> <label for="emailCheckBox1">Checkbox</label><br />
<p><label for="emailTextBox">Text Box</label><br /><input type="text" id="emailTextBox" name="emailTextBox" value="<?php echo $emailTextBox; ?>" /></p>
<?php
}
public function bigMetaBox() // here we draw a big textarea box for simple raw text
{
global $post;
$custom = get_post_custom($post->ID);
$textVersion = $custom['text_version'][0];
?>
<input type="hidden" name="demo_noncename" id="demo_noncename" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" /><br />
<textarea name="text_version" style="width:100%;height:200px;"><?php echo $textVersion; ?></textarea>
<?php
}
Step 4: Again, a single function to take care of it all, use register_taxonomy().
public function createCustomTaxonomy() // add a categorization to our custom post type
{
$labels = array('name' => 'Departments',
'singular_name' => 'Department',
'search_items' => 'Search Departments',
'all_items' => 'All Departments',
'parent_item' => 'Parent Department',
'parent_item_colon' => 'Parent Department:',
'edit_item' => 'Edit Department',
'update_item' => 'Update Department',
'add_new_item' => 'Add New Department',
'new_item_name' => 'New Department Name'
);
register_taxonomy('department',array('mailtemplate'), array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'department' )
));
}
Step 5: Hook into the save_post hook with a real quick easy function to read the $_POST and save data. This is where you would validate and sanitize.
// this is how we save our custom fields (in the meta boxes)
public function savePostData( $post_id ) {
if ( !wp_verify_nonce( $_POST['demo_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
// Check permissions
if ( 'mailtemplate' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
} else {
return $post_id;
}
$fields = array('emailCheckBox1','emailTextBox','text_version');
foreach ($fields as $field) {
if (!update_post_meta($post_id, $field, $_POST[$field])) {
add_post_meta($post_id, $field, $_POST[$field], true);
}
}
}
Step 6: You can customize the columns and data displayed on the edit page by hooking into the action manage_posts_custom_column and using a custom filter manage_edit-{custom_post_id}_columns, in my example the filter is manage_edit-mailtemplate_columns. The easiest way I think to create a custom display on the public pages, I have attached a functions.php theme file for your theme. The snippet registers a custom template, which then you can do what you want to display the email template on your public blog.
// these two functions change the display fields and data on the edit page (the list of all templates)
function editColumns($columns)
{
$columns = array(
"cb" => "<input type=\"checkbox\" />",
"title" => "Email Template",
"p_textbox" => "Text Box",
"p_checkbox" => "Check Box",
"p_author" => "Author"
);
return $columns;
}
function customColumns($column)
{
global $post;
$custom = get_post_custom($post->ID);
switch ($column)
{
case "p_textbox":
echo $custom["emailTextBox"][0];
break;
case "p_checkbox":
echo $custom["emailCheckBox1"][0];
break;
case "p_author":
echo get_author_name($post->post_author);
break;
}
}
}
And now to instantiate the class, and add in all the actions.
// Run Plugin
$demoPlugin = new wp30demo();
add_action('init',array(&$demoPlugin,'createCustomPostType'));
add_action('init',array(&$demoPlugin,'createCustomTaxonomy'));
add_action('save_post', array(&$demoPlugin,'savePostData'));
add_filter('manage_edit-mailtemplate_columns', array(&$demoPlugin,'editColumns'));
add_action('manage_posts_custom_column', array(&$demoPlugin,'customColumns'));
And the functions.php file.
<?php
add_action("template_redirect", 'mailtemplate_redirect');
// Template selection
function mailtemplate_redirect()
{
global $wp;
global $wp_query;
if ($wp->query_vars["post_type"] == "mailtemplate")
{
// Let's look for the mailtemplate.php template file in the current theme
if (have_posts())
{
include(TEMPLATEPATH . '/mailtemplate.php');
die();
}
else
{
$wp_query->is_404 = true;
}
}
}

GooglePlus
Twitter
RSS
LinkedIn
Picasa
Pingback: How to Use New Wordpress 3.0 Features That Will Save You Tons of … | Design Blog