Day Three – Creating a Custom Post Type and Adding a Meta Box

In the previous two days of this tutorial series we focused on setting up the plugin and creating the table in our database. This tutorial we are going to create our custom post type that will be for our events and create a meta box to contain the start and end times. Okay, maybe still a bit of overlap from previous posts, but we need to set these up before we can more forward.

Creating the Event Post Type

If you haven’t read our tutorial on creating a custom post type class, we are going to use this class to do the work. It is pretty simple, but if you are not up to speed on how to use this class, just read that post. It is pretty detailed and if you have any questions just post them in the comments.

The first thing we need to do is to create a file to hold our class and add it to our plugin folder. I called our new file event_post_type.php and I also renamed the custom post type class to event_post_type. So not to go back through the previous tutorial on this here is the code below:

include(EVENT_CALENDAR_DIR . 'event_post_type.php');

$config = array(
  'single' => 'Event',
  'plural' => 'Events',
  'type'  => 'event',
  'supports' => array('title', 'editor', 'excerpt')
);

$event_post_type = new Event_post_type;

$event_post_type->init($config);

add_action('init', array(&$event_post_type, 'add_post_type'));
add_filter('post_update_messages', array(&$event_post_type, 'add_messages'));

You can see that we did use our constant, EVENT_CALENDAR_DIR, to include our file via the absolute path. We then created an options array and created a varible representing a new instance our class. Since I wanted to use a title, the editor, and an excerpt, I passed each of those to ‘support’ in the config array. I then took the $config array and passed it to the init method of the class. Then the add_action function was called to hook onto the ‘init’ hook. A reference was use with our class variable and the method we wanted to call, add_post_type. The same was done with add_filter to call the method ‘add_messages’.

After this is complete you can go to the admin and see the post type has been added. And it will look like this:

Adding a Meta Box to Our Event Post Type

To add a meta box to our event post type we need to create two user defined functions. The first will be used to just register the meta box and the second will be the actual content in the meta box. If you have never used the add_meta_box function here is a breakdown the function and the parameters it will accept:

add_meta_box($id, $title, $callback, $page, $context, $priority, $callback_agrs);

  • $id – this simply represents the id that you would like to assign to your meta box, maybe for CSS purposes or whatever.
  • $title – this is the displayed title of your meta box.  For example, the meta box for your excerpt has the title of “Excerpt”.
  • $callback – This is the function that will be called with when the meta box is displayed.  It will contain all the content that you want in your meta box.  And in this case will be the event start and end times and dates.
  • $page – this is the post type that we want our meta box to be displayed in.  For this we are going to input ‘event’.
  • $context – context is where one the page your meta box will be displayed.  We are going to display it in the right side bar so ‘side’.
  • $priority – this can be used to determine how high on the page the meta box will be displayed.  We won’t even include this so it will default to last.
  • $callback_agrs – these are arguments that you want to pass to your callback function.  We won’t use this since we will just call in the global $post variable into our function, but we could pass the variable here if we wanted.

So here is the first part:

add_action("admin_init", "event_fields");

function event_fields(){
  add_meta_box('event_meta', 'Event Options', "event_meta_options", "event", "side");
}

Above we just hooked into the admin_init hook to then call our user defined function event_fields which will add the meta box to the events page. The meta box will have the title of “Event Options” and the callback function that will contain the content is another user define function which is below. Also, notice the context is ‘event’, the post type.

Here is our call back function event_meta_options:

function event_meta_options(){

  global $post;

  $table = "<table>";
  $table .= "<tr><td><label for='start_date'>Start Date</label></td><td><input class='date_field' type='text' name='start_date' value='' /></td></tr>";
  $table .= "<tr><td><label for='end_date'>End Date</label></td><td><input class='date_field' type='text' name='end_date' value='' /></td></tr>";
  $table .= "<tr><td><label for='start_time'>Start Time</label></td><td><input class='time_field' type='text' name='start_time' value='' /></td></tr>";
  $table .= "<tr><td><label for='end_time'>End Time</label></td><td><input  class='time_field' type='text' name='end_time' value='' /></td></tr>";
  $table .= "<tr><td><label for='event_visible'>Show Event:</label></td><td><select name='event_visible'><option value='1'>Yes</option><option value='0'>No</option></select></td></tr>";
  $table .= "</table>";
  
  echo $table; 
}

You notice that I first called in the global post variable, we won’t use this now but in a future tutorial. Also you see that I created a table that holds the fields and labels.

So far this is what you would get:

What’s next?

A meta box is just great and maybe I just repeat myself a bit. But next time we will focus on adding JavaScript to the inputs of our meta box.

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
Posted in Plugin Development | Tagged , | 2 Comments

Day Two – Design and Creating our Database Table

In day one of this series we focused only on setting up a canvas so to say for our plugin. This tutorial will be dedicated to creating our table that we will use to store our event information. We will first cover the design our table and then we will use WordPress to create our table.

The Design Our Events Table

In a previous post, on how to create a meta box with a datapicker, we just took the information some information and stored it in the post meta table. The question that you need to answer is this the best way to store and use this data. We were just taking a date and storing as a string, but the issue might be how you can use that to organize the posts. You could definitely craft some method using this information, but for this tutorial, we are going to create a new table within our WordPress to store the event information like the start date. It definitely seems easier and there is the added benefit that we can use the power of MySQL to organize our events.

Here are the fields we are going to use: event_id, post_id, start_date, end_date, start_time, end_time, and event_visible. The event_id field will be an auto incrementing unique key. Post_id will be our link back to the post table. The posts will where we store the content and we will need this relationship to perform our queries. The fields, start_date and end_date, will be stored in the MySQL date format. The start_time and end_time fields will be stored in the MySQL time format. The last field, event_visible, will be Boolean that will determine if the event is visible on the calendar.

Creating Our Events Table

Now that we have designed of our table the next thing is to code a user defined function that will create the table. This function will first call in the $wpdb global database object. If you haven’t used $wpdb before there is extensive documentation on WordPress.org. Here is our function:

register_activation_hook(__FILE__, 'create_events_table');
  
function create_events_table(){
  //global wordpress database object
  global $wpdb;

  //The table to store the data
  $table = $wpdb->prefix . "our_events";
  
  if($wpdb->get_var("show tables like '" . $table . "'") !== $table){
    $sql = "CREATE TABLE " . $table . " (
      event_id bigint(20) NOT NULL AUTO_INCREMENT,
      post_id bigint(20) NOT NULL,
      start_date date NOT NULL,
      end_date date NOT NULL,
      start_time time NOT NULL,
      end_time time NOT NULL,
      event_visible tinyint(1) DEFAULT '1' NOT NULL,
      UNIQUE KEY id (event_id)
    )";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
  }
}

Now, if we deactivate our plugin and then reactivate our plugin, WordPress will actually create the table for us.

What Now?

A table is nice and all but really isn’t doing anything for us. This means in the next tutorial we will create a meta box and event class to save the information.

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
Posted in Plugin Development | 1 Comment

An Event Calendar Plugin Series Begins

Over the next few days we are going to create several tutorials on how to create a custom event calendar.  These will be an in-depth on not only how to create a custom calendar but WordPress in general.  We will cover from the most basic concepts like setting up a plugin to more advanced topics such as rewrite rules.   This day will cover creating the file structure where will build the plugin, registering the plugin with WordPress, and creating constants we will use throughout our plugin.

Creating our files

To begin, I create a folder within our plugins directory.  I named the folder the name of the plugin that we will be creating.  Also, I create a new PHP file within this directory with the same name as the plugin, custom_event_calendar.  This will be our main plugin file, where we will register the plugin with WordPress and run many of the main functions of our plugin.  Here is the folder and the file that we just created:

Registering Our Custom Event Calendar with WordPress

Now that we have a bit of a canvas to work, the next step is to actually register the plugin with WordPress.  This step is pretty simple and is covered in a previous tutorial called The Beginning Steps to Writing Your Own WordPress Plugin.  This might be pretty brief so if you need reference that previous post.

To have WordPress recognize your plugin you need to include some commented out lines of code at the beginning of your main plugin file.  Here is the code that I included in the file custom_event_calendar.php:

<?php
/*
Plugin Name: Custom Event Calendar
Plugin URI: http://www.wpinsideout.com
Author: Kyle G.
Author URI: http://www.wpinsideout.com
Version: 1.0
Description: A plugin to manage your sweet events.
*/

This code will now register the plugin with WordPress and when we activate it we will get this:

Creating Constants

Constants are a great thing to have when you are creating a plugins. It allows us to type less and we don’t have to worry about mistakes in our paths to our files so it is consistent. For these reasons, I am going to create two constants using the plugin’s name in the constant. This will be appended with either URL or DIR, with URL referencing the URL path and DIR referencing the absolute path. If you are not familiar with the difference between the two, you need to read up on the topic because for different situations we will need to use one or the other.

Here are the two constants I created:


if(!defined('EVENT_CALENDAR_URL'))
  define('EVENT_CALENDAR_URL', WP_PLUGIN_URL . 'custom_event_calendar/');
  

if(!defined('EVENT_CALENDAR_DIR'))
  define('EVENT_CALENDAR_DIR', WP_PLUGIN_URL . 'custom_event_calendar/');

The two constants from above actually are created using two constants from WordPress, WP_PLUGIN_URL and WP_PLUGIN_DIR. We could use this we creating our paths but I find it a bit quicker and prevents more possible if we have our own constants.

Moving Forward – Day Two

This might not have been a real exciting day, and maybe you could even skipped it if you are already familiar with the topics cover. The next day we will cover our database design and how to use WordPress to create a database.

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
Posted in Plugin Development | Leave a comment

Our First Plugin Released

I have just complete and uploaded our first plugin. It is a super simple user login redirect hence the name simple login redirect. It adds a section of content to the user’s profile that allows you to specify a redirect when the user logs in.

It is simple because there really isn’t that many options. There is no bulk redirects. There is no error login redirection. Maybe in the future there will be a need or addition of these features. It just redirects users to a specified URL from their profile.

What if there is no URL specified? Well good question. Then, there will be no redirection and the login will just follow the standard process.

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
Posted in Announcements | Tagged | Leave a comment

Five Ways to Control the Length Of Your WordPress Excerpt

Do you want an excerpt that is either longer or shorter? There are several method to limit or length your excerpt and we will look at 5 in detail. Some are simple and other will be a bit more complex. Each has their pluses and minuses, so you can choose the method that suits you best.

Method One – Filtering the Excerpt Length

The first method involves adding a filter to the excerpt length. If you are not familiar with filter hooks, this is a great method for you to get your feet wet.

Steps to filtering the excerpt length

  1. We must first create a user defined function, which I called change_excerpt_length in our function.php file in our active theme.
  2. This function can accept a variable which will represent the actual excerpt length, but we really do not need for this example.
  3. Our function just needs to return an integer. This integer represents the number of words we want our excerpt to be.
  4. Add add_filter function in our function.php file in our active theme. We need to hook onto excerpt_length and reference our function.

function change_excerpt_length($length){
  return 10;
}

add_filter('excerpt_length', 'change_excerpt_length');

The result will be an excerpt limited to the length we specified in our user defined function, which in this case is 10 words.

Positives
  • This method is super simple. You can change the length of your excerpt with 4 lines of code.
  • It changes all the excerpts lengths at once.
  • It does allow us to override the length by inputting an excerpt in excerpt meta box in the admin post screen
Negatives
  • This method lacks flexibility. Since this will change the length of every excerpt, you will not be able to have one excerpt longer than another.

Method Two – Explode the Excerpt

This method will use another filter to modify the_excerpt itself.

How to shorten the excerpt using the PHP function – explode
  1. 2. We need to create a user defined function which I call my_excerpt_filter, that accepts one parameter that represents the actual excerpt.
  2. Inside our function, we must strip the tags to prevent any HTML from not being closed when we echo our excerpt at the end our function.
  3. We then can explode the excerpt by the blank spaces that represent the spaces between the words. This function will create an array which we assigned to variable $strs
  4. Then we will implode the array using array_splice function after wrapping in paragraph tags.
  5. 6. We need to now use a filter hook in our functions.php file to hook onto the_excerpt and reference our function.

function my_excerpt_filter($excerpt){
  $excerpt = strip_tags($excerpt);

  $strs = explode(" ", $excerpt);

  echo "<p>" . implode(' ', array_splice($strs, 0, 10)) . "</p>";
}
add_filter('the_excerpt', 'my_excerpt_filter');

The result will be a excerpt that is limited to the number of words defined with in the third parameter of the array_splice function.

The positives for using explode to limit the length of the excerpt
  • They are exactly the same as the first method
The negatives for using explode to limit the length of the excerpt
  • If we want an excerpt that is longer than the standard 55 words, this function will not work.
  • If we have an excerpt that we actually input in the excerpt meta box in the post screen, this method will not allow use do display all the content. It will be limited.
  • The length is coded into our filter function. This limits our ability to change the length without changing our function.
  • There is potential formatting issues by stripping the tags. If there is a need for an excerpt to be two paragraphs this method will not support the formatting. More on this later.

Method Three: Use Some Regex to Limit Your Excerpt

This example uses the preg_match PHP function to create a similar effect as above.

How to use preg_match to limit your excerpt
  1. Again we are going to create a user defined function within our function.php file in the active theme. For this example the function will be call regex_my_excerpt. This will accept one parameter which will be the current excerpt.
  2. Again strip the tags as in example two for the same reason.
  3. Echo the 0 offset in the matches array wrapped in paragraph tags.
  4. 4. Use a filter hook for the_excerpt in the function.php file and reference our user defined function called regex_my_excerpt.

function regex_my_excerpt($excerpt){
  $excerpt = strip_tags($excerpt);

  preg_match('/^\s*+(?:\S++\s*+){1,10}/', $str, $matches);

  echo "<p>" . $matches[0] . "</p>";
}
add_filter('the_excerpt', 'regex_my_excerpt');

The excerpt will be limited buy second number wrapped in the curly brackets in our regex expression.

Positives for using regex to limit your excerpt
  • Same reasons as above
  • Can allow for additional formating like if you have an excerpt that needs to be two paragraphs. (Not in this example but will be later discussed
Negatives for using regex to limit your excerpt
  • It has the negatives from the previous examples.
  • It adds a level of complication by using a regular expression to limit the length of the excerpt.

Method Four: Using the Post Global to Create a Custom Excerpt

This method actually uses the post object to create a custom excerpt.

How to use the post global for a custom excerpt
  • Create a user defined function with the function.php file in our active theme which I called my_custom_excerpt.
  • Call in the global variable for the post object.
  • Test to see if there is a excerpt already set and if there is echo that excerpt. This deals with the issue of a user inputted excerpt in the post screen in the admin.
  • If the excerpt is empty, then we must create one using the content. We again strip the tags to begin.
  • Then we use the regex from above to match the number of words we want.
  • We then can echo our match from our matches array. Wrapped in paragraph tags.
  • Use a filter hook for the_excerpt in the function.php file and reference our user defined function called my_custom_excerpt.
  • function my_custom_excerpt(){
      global $post;
    
      if(!empty($post->post_excerpt)){
        echo "<p>" . $post->post_excerpt . "</p>";
      }
      else{
        $content = strip_tags($post->post_content);
    
        preg_match('/^\s*+(?:\S++\s*+){1,10}/', $content, $matches);
    
        echo "<p>" . $matches[0] . "</p>";
      }
    }
    add_filter('the_excerpt', 'my_custom_excerpt');

    Benefits for using the post global to create a custom excerpt
  • Has the same benefits as the methods listed above.
  • This method allows for excerpts that are longer than 55 words.
  • One large benefit is that is deals with the user defined excerpts for a post. If there is one then use that if not lets create one.
    • Negatives for using the post global to create a custom excerpt
  • Again, this method has the same negatives as above
  • Method Five: Create a Function that Replaces the_excerpt Function

    This method we create a new function that takes the place of the_excerpt function.

    How to create a custom function to replace the_excerpt
    1. We need to create a user defined function in function.php of our active theme.
    2. This function will accept two parameters. The first will represent the length of our excerpt. The second is the last character of our excerpt, which we will set to a default of …
    3. We then will modify the regex from example four to allow use to set the length of the matched string.
    4. We will then wrap the result in paragraph tags with the end character in place.
    5. We next need to replace the_excerpt where ever we want with our new function and define our length with every instance.

    function custom_the_excerpt($length, $end_char = '&#8230;'){
           global $post;
    
        if(!empty($post->post_excerpt)){
          echo "<p>" . $post->post_excerpt . "</p>";
        }
        else{
          $content = strip_tags($post->post_content);
    
          preg_match('/^\s*+(?:\S++\s*+){1,' .$length . '}/', $content, $matches);
    
          echo "<p>" . $matches[0] . "</p>";
        } 
      }

    The length of our excerpt will not be whatever we want to pass this function.

    Benefits of our custom function
    • We can select the length our excerpt on the fly.
    • Most flexible out of all the examples
    Negatives of our custom function
    • We have to manually change out the_excerpt’s functions. This means finding all them in the theme and switching them to this function. Could take a little time.

    An issue with methods 2 Through 5

    There is a potential annoying issue that can be discussed on the side. It is what if you have an excerpt that consists of two paragraphs. We just wrapped our results in a single paragraph tag and called it good. This will cause a formatting issue. Well, we would actually need to take a bit further and use some more regex to match new lines that normally WordPress would change into either a break tag or a new paragraph. We can do that using a bit more regex. But I am only going to this using example five.

    function custom_the_excerpt($length, $end_char = '&#8230;'){
        global $post;
    
        if(!empty($post->post_excerpt)){
          $excerpt = preg_replace("/\n/", "</p>\n\n<p>", $post->post_excerpt);
    
          echo "<p>" . $excerpt . "</p>";
        }
        else{
          $content = strip_tags($post->post_content);
    
          preg_match('/^\s*+(?:\S++\s*+){1,' .$length . '}/', $content, $matches);
    
          $excerpt = preg_replace("/\n/", "</p>\n\n<p>", $matches[0]);
    
          echo "<p>" . $excerpt . $end_char . "</p>";
        } 
      }

    This method will find the new lines and convert them to paragraph tags preserving the formatting. And it will only work on the methods that use regex. This means with the explode method you are out of luck.

    How about a plugin

    There are many plugins out there that will change the length of excerpt. Maybe one of the most popular is a plugin called “The Excerpt re-loaded.” It comes with a ton of options and is pretty simple to use.

    Isn’t About Time For An Upgrade of the_excerpt

    The excerpt is a nice feature of WordPress. It is a method to get people to a teaser about your post to encourage them to read the whole thing. Maybe though the next version of the_excerpt should come standard with a parameter to change the length. It would be nice compared to having all these methods to change the length.

    SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
    Posted in Uncategorized | Tagged , , | 2 Comments

    Seeing WordPress Rewrite Rules

    If you have ever wondered how permalinks and the WordPress rewrite class work, there is no better way to find out than to display the WordPress rewrite rules. If you are unfamiliar with the rewrite class, it provides the function that takes the URL you or your visitor are looking for and decodes it. After decoding, WordPress then knows what content you are looking for. Is it a page, post, or category, etc?

    Why should you see what the WordPress rewrite rules are?

    Being able to see the structure of the rewrite rules will allow you to first get a better understanding of WordPress and the underlying functionality of WordPress. Second, you will be able to create your own custom URL’s that you can use in Plugins. Which is the real point of the this post as we will later look at adding our own rewrite rules to WordPress in a plugin.

    How are we going to see the WordPress rewrite rules?

    What we are going to do is use an action hook to call a function that will display our rewrite rules. I like to add an action to the wp_footer hook and call a function call “show_rewrite_rules”. Here is the setup:

    add_action('wp_footer', 'show_rewrite_rules');
    
    function show_rewrite_rules(){
    
    }

    We next need pull in the global variable that represents the WordPress rewrite class: $wp_rewrite. After we have that varaible pulled into our function displaying the WordPress rewrite rules is super easy. We can just echo a pre tag then use the print_r() PHP function and pass it $wp_rewrite->rules. This is an array of rewrite rules for our WordPress site. After doing that we can echo the close pre tag and we are done.

    Here is the completed function to display our rewrite rules:

    add_action('wp_footer', 'show_rewrite_rules');
    
    function show_rewrite_rules(){
      global $wp_rewrite;
      echo "<pre>";
      print_r($wp_rewrite->rules);
      echo "</pre>";
    }

    That is pretty much it now when we visit the front end of the site we will get an array at the bottom of our page that will show us our rules:

    Like mentioned above, understand WordPress’ rewrite rules will give a greater understand of the underlying methods of WordPress and it is great for plugin development. The use of this function is great when you are trying to add your own rewrite rules. It will allow you to see if your rules are being added and if not if the rules need to be flushed.

    SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
    Posted in Development | Leave a comment

    A Custom Meta Box with a Datepicker

    This tutorial will cover how to add a meta box to your custom post type for saving a date. We will need to create the meta box which will contain a field to represent the date. The input for the date will accept a standard date format but we want to add a nice user interface, so we are going to add a JavaScript datepicker JavaScript to the input box. This will make the selection of a date very easy. After all that we are going to save the information to the post meta table.

    What is a meta box

    A meta box is a section of content which can be added to the post, page, and or your custom post type. Meta boxes help locate certain areas of content like areas of content such as the excerpt or categories. For this tutorial, we are going to have a custom post type called ‘event’ and we need to have a save the date for the event.

    The first thing we need to do is to have a custom post type called ‘event’. To make it quick, we can use our custom post type class from a previous tutorial to quickly add the post type. I am going to add a folder to my current theme called “classes” to store my custom post type class. After creating the PHP file called “add_custom_post_type.php”, I will include this file in my functions.php file of my active theme. See below for the code from my functions.php file:

    include('classes/custom_post_type.php');
    
    $options = array(
      'single' => 'Event',
      'plural' => 'Events',
      'type' => 'event'
    );
    
    $customPost = new My_post_type_class;
    
    $customPost->init($options);
    
    add_action('init', array(&$customPost, 'add_post_type'));
    add_filter('post_updated_messages', array(&$customPost, 'add_messages'));

    After registering the custom post type for events, you will see the tab for our events has been added to the admin:

    Creating our meta box

    Now, that the custom post type is ready, we need to use an action hook. We will hook on to the admin initialization with the function’s name that will register our meta box. I called the function “register_event_meta”. This is where we are so far.

    add_action("admin_init", "register_event_meta");
    
    function register_event_meta(){
    
    }

    Now, inside our register_event_meta function we are going to use the function add_meta_box(). This function will create a section of content on a post, page, and or custom post type page. It accepts a few arguments. Here is the function with a review of the arguments.

    add_meta_box( $id, $title, $callback, $page, $context, $priority, $callback_args );

    • $id – This is the css id for the meta box. It allows you to style as you need.
    • $title – This is will use to populate a title of your meta box.
    • $callback – This is the name of the function we will call that will display our meta box content.
    • $page – This is a string that indicates that the post type. So if it is given a value of post. The meta box will show up on the add/edit post pages. If give a value of “event”, it would show up on the event edit/add screens.
    • $context – This represents the place on within your add/edit screens. With the three options being: “normal”, “advanced”, and “side”.
    • $priority (optional) – the priority will indicate how high your meta box will show up on the page. You can pass two different values: “high” or “low”
    • $callback_args (optional) – This is an array of arguments that your callback function would accepts.

    Displaying our meta box

    We need to create our callback function which we call “event_meta_options”. This will be the function that actually echos content and contains our custom input. So here is the code so far below:

    add_action('admin_init', 'register_event_meta');
    
    function register_event_meta()
    {
      add_meta_box('meta_options', 'Event Start', 'event_meta_options', 'event', 'side', 'low');
    }
    
    function event_meta_options()
    {
      echo "<label for='start_date'>Start:</label><input type='text' name='start_date' value='' />";
    }

    Here is what we get:

    Now we need to add an action hook to “save_post”, where we will call a function that will save our function to the post_meta database. Also, we need to get this information from the database to repopulate the input with our saved data. Here is the code:

    function event_meta_options()
    {
      global $post;
      
      $start = get_post_meta($post->ID, '_event_start', TRUE);
    
      echo "<label for='start_date'>Start:</label><input type='text' name='start_date' value='{$start}' />";
    }
    
    add_action('save_post', 'save_event_start');
    
    function save_event_start()
    {
      global $post;
      
      if($post->post_type == 'event')
      {
        update_post_meta($post->ID, '_event_start', $_POST['start_date']);
      }
    }

    Now, when our custom post type saves, the input field for start will be saved into the post_meta database. Also, we are getting that value to repopulate the field. Also, a important note, starting the post meta name with “_” to prevent it from being included in the post meta dropdown. Definitely, nice a feature to prevent a long drop down of potential custom field names.

    Add the javascript

    We are now going to incorporate the datapicker script found here: Datepicker. After downloading the files, I am going to place the javascript in a folder in the theme called “js” and the css for the datepicker in the folder for css in the theme. Here is the code:

    function event_javascript()
    {
      global $post;
    
      if($post->post_type == 'event')
      {
        wp_enqueue_script('datepicker', WP_CONTENT_URL . '/themes/twentyten/js/datepicker.js', array('jquery'));  
      }
    }
    
    add_action('admin_print_styles', 'event_css');
    
    function event_css()
    {
      global $post;
      
      if($post->post_type == 'event')
      {
        wp_enqueue_style( 'datepicker', WP_CONTENT_URL . '/themes/twentyten/css/datepicker.css');
      }
    }

    Without going into to much detail about enqueue script and enqueue style, enqueue is a method to have WordPress manage what files are being referenced. Also, with JavaScript it allows you to pass the libraries that will be need to run the script. In this case, it is jQuery. Also, you see that we are testing to see if the post type is “event” with both. This is just a method to prevent the loading of these items on pages that don’t need them in the admin.

    Now we need to assign an id to our field and call the JavaScript. So I will give the field the id of “event_start”. Just to make things easy I will also call the JavaScript right below it.

    Here is the entire code with the modifications mentioned above:

    function register_event_meta()
    {
      add_meta_box('meta_options', 'Event Start', 'event_meta_options', 'event', 'side', 'low');
    }
    
    function event_meta_options()
    {
      global $post;
      
      $start = get_post_meta($post->ID, '_event_start', TRUE);
    
      echo "<label for='start_date'>Start:</label><input id='event_start' type='text' name='start_date' value='{$start}' />\n";
      
      echo '<script type="text/javascript">jQuery(document).ready(function(){jQuery("#event_start").simpleDatepicker();});</script>';
    }
    
    add_action('save_post', 'save_event_start');
    
    function save_event_start()
    {
      global $post;
      
      update_post_meta($post->ID, '_event_start', $_POST['start_date']);
    }
    
    add_action('admin_print_scripts', 'event_javascript');
      
    function event_javascript()
    {
      global $post;
    
      if($post->post_type == 'event')
      {
        wp_enqueue_script('datepicker', WP_CONTENT_URL . '/themes/twentyten/js/datepicker.js', array('jquery'));  
      }
    }
    
    add_action('admin_print_styles', 'event_css');
    
    function event_css()
    {
      global $post;
      
      if($post->post_type == 'event')
      {
        wp_enqueue_style( 'datepicker', WP_CONTENT_URL . '/themes/twentyten/css/datepicker.css');
      }
    }

    Here is the final product:

    SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
    Posted in Advanced, Development, Plugin Development | Tagged , | 17 Comments

    Advanced Custom Post Types – PHP Class Integration

    It was quite apparent to me that the addition of custom post types made this version of WordPress the most powerful yet. When I first saw their power, I began adding custom post types immediately. One recent theme I developed took full advantage of them having a total of 3 custom post types. And then I wrote a plugin that used custom post types and custom taxonomies. It was soon apparent to me, I was repeating myself a lot and the code also began to become lengthy. The solution I came up with was to create a custom post type class.

    Why A Class For Custom Post Types and Project Overview

    Having a class to manage these will take full advantage of the reliability of object oriented PHP and made adding custom post types a mater of a few lines of code. You will do less coding because it was reusable.

    To begin we going to do this in the context of creating a plugin. It will have several functions but one main functions will be to add a custom post type to manage our products.

    Also the code we will be using for our custom post type class methods are found in a previous post on adding custom post types.

    Registering Our Plugin

    If you have not created a plugin before there are few steps but here it is short in sweet:

    • Create a folder in your plugins directory called: our_products
    • Inside that folder create a PHP file with the same name: our_products.php. See below:

    • Next we are going to add the code to register the plugin:

    /*
    Plugin Name: Our Products
    Plugin URI: http://www.wpinsideout.com
    Author: Kyle G.
    Author URI: http://www.wpinsideout.com
    Description: Example project to show the use of a custom post type and custom taxonomy class
    Version: 1.0
    */

    Now our plugin is registered with WordPress and if we go to the plugins tab in the admin we will see the plugin is available for activation.

    If activate it nothing will happen. But as we code we can just refresh to see the changes our plugin is making.

    Start Creating Our Class

    We are now going to create a new PHP file in our plugin directory called: add_post_types.php. Inside this file we are going to create a class with the same name as the file. Here is the beginning code for the class:

    
    <?php
    
    class Add_post_types {
    
    }

    We are now going to need a few variables and a function that accepts an associative array to assign values to these variables. Here is our custom post type class so far:

     
    <?php
    
    class Add_post_types {
    
      var $single; //this represents the singular name of the post type
      var $plural; //this represents the plural name of the post type
      var $type; //this is the actual type
    
      function init($options){
        foreach($options as $key => $value){
          $this->$key = $value;
        }
      }
    

    To understand what is going on here in our plugin we are going to pass an associative array with the keys having the same name as the classes variables. When we call the init method and pass our options array, this method will assign the values to the classes variables.

    Now we need to create our first method to add the post type and we can take the example from our tutorial on custom post types. We want to take the function called “my_widget_post_type_init” and we can paste it directly into our class.

    We are going to do several edits to this function. First, I am going to change its name to “add_post_type”. Then I am going replace every instance of the word “widget” in the labels array with “$this->single”. Then, I am going to replace every instance in the labels array of the word “widgets” with “$this->plural”. Lastly, I am going change “widget” in the register_post_type function to “$this->type”

    If you are unfamiliar with object oriented PHP, using $this->single, $this->plural, or $this->type will take the class variables and use it in this method. It allows use to assign value to these variables in the init method and then be able to use it in this method. Here is the class so far with the edited functions

    :

     
    <?php
    
    class Add_post_types {
    
      var $single; //this represents the singular name of the post type
      var $plural; //this represents the plural name of the post type
      var $type; //this is the actual type
    
      function init($options){
        foreach($options as $key => $value){
          $this->$key = $value;
        }
      }
    
      function add_post_type(){
        $labels = array(
          'name' => _x($this->plural, 'post type general name'),
          'singular_name' => _x($this->single, 'post type singular name'),
          'add_new' => _x('Add ' . $this->single, $this->single),
          'add_new_item' => __('Add New ' . $this->single),
          'edit_item' => __('Edit ' . $this->single),
          'new_item' => __('New ' . $this->single),
          'view_item' => __('View ' . $this->single),
          'search_items' => __('Search ' . $this->plural),
          'not_found' =>  __('No ' . $this->plural . ' Found'),
          'not_found_in_trash' => __('No ' . $this->plural . ' found in Trash'),
          'parent_item_colon' => ''
        );
        $options = array(
          'labels' => $labels,
          'public' => true,
          'publicly_queryable' => true,
          'show_ui' => true,
          'query_var' => true,
          'rewrite' => true,
          'capability_type' => 'post',
          'hierarchical' => false,
          'menu_position' => null,
          'supports' => array('title','editor','author','thumbnail','excerpt','comments')
          );
        register_post_type($this->type, $options);
      }
    }
    

    Next we are going to take the function called “widget_message” found in our custom post type tutorial. We are again to change a few things. First we are going to change the name of the function to “add_messages”. Second we are going to change the key in the messages array to “$this->type”. Third, we are going to replace every instance of “widget” with “$this->single” and every instance of “widgets” with “$this->plural”. Here is the completed class:

     
    <?php
    
    class Add_post_types {
    
      var $single; //this represents the singular name of the post type
      var $plural; //this represents the plural name of the post type
      var $type; //this is the actual type
    
      function init($options){
        foreach($options as $key => $value){
          $this->$key = $value;
        }
      }
    
      function add_post_type(){
        $labels = array(
          'name' => _x($this->plural, 'post type general name'),
          'singular_name' => _x($this->single, 'post type singular name'),
          'add_new' => _x('Add ' . $this->single, $this->single),
          'add_new_item' => __('Add New ' . $this->single),
          'edit_item' => __('Edit ' . $this->single),
          'new_item' => __('New ' . $this->single),
          'view_item' => __('View ' . $this->single),
          'search_items' => __('Search ' . $this->plural),
          'not_found' =>  __('No ' . $this->plural . ' Found'),
          'not_found_in_trash' => __('No ' . $this->plural . ' found in Trash'),
          'parent_item_colon' => ''
        );
        $options = array(
          'labels' => $labels,
          'public' => true,
          'publicly_queryable' => true,
          'show_ui' => true,
          'query_var' => true,
          'rewrite' => true,
          'capability_type' => 'post',
          'hierarchical' => false,
          'menu_position' => null,
          'supports' => array('title','editor','author','thumbnail','excerpt','comments')
          );
        register_post_type($this->type, $options);
      }
    
      function add_messages ( $messages ) {
    
        $messages[$this->type] = array(
        0 => '', 
        1 => sprintf( __($this->single . ' updated. <a href="%s">View ' . $this->single . '</a>'), esc_url( get_permalink($post_ID) ) ),
        2 => __('Custom field updated.'),
        3 => __('Custom field deleted.'),
        4 => __($this->single . ' updated.'),
        5 => isset($_GET['revision']) ? sprintf( __($this->single .' restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
        6 => sprintf( __($this->single . ' published. <a href="%s">View ' . $this->single . '</a>'), esc_url( get_permalink($post_ID) ) ),
        7 => __('Book saved.'),
        8 => sprintf( __($this->single . ' submitted. <a target="_blank" href="%s">Preview ' . $this->single . '</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
        9 => sprintf( __($this->single . ' scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview ' . $this->single . '</a>'),
          date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
        10 => sprintf( __($this->single . ' draft updated. <a target="_blank" href="%s">Preview ' . $this->single . '</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
        );
    
        return $messages;
      }
    
    }
    

    Now that we have our class, we just need to add our post type in our main plugin file. Here are the steps:

    1. Include the file containing our class.
    2. Create a new instance of our class and assign it to a variable.
    3. Create our options array.
    4. Pass our options array to our init method.
    5. use the add_action function to hook onto the initialization of WordPress and call our add_post_type method through the use of a reference.
    6. We then need to use the add_filter function to filter ‘post_updated_messages’ using a reference to our class and method.

    Here is the complete code below:

    
    include('add_post_types.php');
    $create_post_type = new Add_post_types;
    
    $options = array(
      'single' => 'Product',
      'plural' => 'Products', 
      'type' => 'product'
    );
    
    $create_post_type->init($options);
    
    add_action('init', array(&$create_post_type, 'add_post_type'));
    add_filter('post_updated_messages', array(&$create_post_type, 'add_messages'));
    

    That is it. Here is the result:

    You see that the type has been added. All the labels are correct and the message display product. To really show you how quick and easy it is for you now, I’ll add a second for a custom post type of services. Here is the code:

    
    include('add_post_types.php');
    $create_post_type = new Add_post_types;
    
    $options = array(
      'single' => 'Product',
      'plural' => 'Products', 
      'type' => 'product'
    );
    
    $create_post_type->init($options);
    
    add_action('init', array(&$create_post_type, 'add_post_type'));
    add_filter('post_updated_messages', array(&$create_post_type, 'add_messages'));
    
    $services_post_type = new Add_post_types;
    
    $options = array(
      'single' => 'Service',
      'plural' => 'Services', 
      'type' => 'service'
    );
    
    $services_post_type->init($options);
    
    add_action('init', array(&$services_post_type, 'add_post_type'));
    add_filter('post_updated_messages', array(&$services_post_type, 'add_messages'));
    

    Now we get this:

    Wrap Up On Using A Custom Post Type Class

    You notice above that I did assign a new variable to create the second post type and that is only way it will work.

    Overall, the coding is kept to a minimum. You can add custom post types fast and consistently. You can also take this class over to over projects and get a jump start on those projects. You can use this in your theme development. Having maybe a folder for your classes and include this file in your functions.php file. Then use your functions.php file to add the post types.

    SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
    Posted in Advanced, Plugin Development | Tagged | 7 Comments

    What is WordPress Taxonomy and How to Add Your Own Custom Taxonomies

    Taxonomy is defined by Wikipedia as practice and science of classification and if you have been using WordPress then you are familiar with taxonomies. Posts are an example of an item that can be classified. You can assign a post a category or give it a tag. Both these methods are the action of classification of your posts in WordPress.

    Up until WordPress 2.3, there were only three available methods of taxonomy available in WordPress:

    • Category Taxonomy – This allows you to group your posts together based on your own classification. WordPress allows you to have a parent-child relationship for your categories. Where you might have a parent category of animals and a child category of manimals.
    • Tag Taxonomy – Tags are term you can associate with your posts. They are very similar to categories but lack the ability to have a parent-child relationship. You can commonly see these displayed in a tag cloud.
    • Link Category – This taxonomy allows you to organize the links you are using. Having links categories, then allows you to get link be category and display them to the user.

    Add Your Own Custom Taxonomies

    As mention above, before WordPress 2.3 there was only three taxonomies available in WordPress, but the change after 2.3 was the ability for you to add your own custom taxonomies. The reasons will vary as to why you want to do this but a quick example is a travel blog that has posts about cities and countries visited throughout the world. If the person post these have a custom taxonomy for countries, they could use that and maybe even go even further and classify by cities in those countries.

    For our purposes, we are going to look at using custom taxonomies with our own custom post type. In a previous post on how to create a custom post type, we create a post type called widget. It sure would be nice to be able to classify our widget base on their attributes, maybe manufacturer or some other quality.

    An Overview of the Register Custom Taxonomy Funciton

    The file we are going to do this in is our functions.php file located in our active theme. We are going to locate the code where we added the custom post type and start working right below it. The function we are going is:

    <?php register_taxonomy($taxonomy, $object_type, $args); ?>

    It accepts three arguments:

    • Taxonomy – This is the name of the actual taxonomy. So if we use the example above, we could have a taxonomy called manimals, where we have categories such as apes or monkeys. If were selling TV’s, we could have a custom taxonomy called televisions and categories that could be LCD or LED.
    • object_type – the object type refers to the object we will be classifying. So posts or in our case widgets.
    • Args – this is an associate array of settings you will need to use to setup the custom taxonomy.
    • Breaking down the arguments
      Here is a list in detail of the possible arguments you can use when creating your custom taxonomy:

    • labels – this is an array of labels that will be used in the admin panel for your custom taxonomy. Below in the example you will see the labels that we will be changing. If not included, the tag labels will be used for taxonomies that lack a parent-child relationship and category labels will be used for the taxonomies that have a parent-child relationshop
    • public – This accepts a true or false and this determines whether or not it should be shown in the admin user interface.
    • show_ui – This accepts a true or false and determines whether or not to generate a user interface for managing your taxonomy.
    • show_tagcloud – This accepts a true or false and determines whether or not show a tag cloud in the user interface.
    • hierarchical – This accepts a true or false. If false the taxonomy will act like a tag. If true the taxonomy will act like a category.
    • update_count_callback – this is an optional name of a function that will update the object of the taxonomy with the taxonomy count.
    • rewrite – this accepts a true or false. If true you will allow WordPress to use its rewrite class for your taxonomy. You then can pass an associate array with the slug you want to use as well as with_front which is a true or false determining to prepend this slug in your URL’s.
    • query_var – You can use this to determine the query var that will be associated with your custom taxonomy.
    • capabilities – this is an associated array of capabilities for your custom taxonomy.

    Our Example

    We are again working in your functions.php file right below our custom post type. First we need to use the add_action function to hook onto the wordpress initialization to have our function that will create our custom taxonomies fire. It looks like this:
    add_action( 'init', 'widget_taxonomies');
    Then we need to create our function called ‘widget_taxonomies’ and call the register_taxonomy() function within our function

    
    function widget_taxonomies(){
      register_taxonomy($taxonomy, $object_type, $args);
    }
    

    Our taxonomy is going to called “brand” and the object_type is going to be our custom post type “widget”.
    
    function widget_taxonomies(){
      register_taxonomy('brand', 'widget', $args);
    }
    

    Now we need to include our arguments, first we will start by creating an array to replace the default labels:
    
    $labels = array(
      'name' => _x( 'Brands', 'taxonomy general name' ),
      'singular_name' => _x( 'Brand', 'taxonomy singular name' ),
      'search_items' =>  __( 'Search Brands' ),
      'all_items' => __( 'All Brands' ),
      'parent_item' => __( 'Parent Brand' ),
      'parent_item_colon' => __( 'Parent Brand:' ),
      'edit_item' => __( 'Edit Brand' ), 
      'update_item' => __( 'Update Brand' ),
      'add_new_item' => __( 'Add New Brand' ),
      'new_item_name' => __( 'New Genre Brand' ),
    ); 
    

    Now that we have out label squared away let’s take a look at the whole thing with a complete argument array.
    
    add_action( 'init', 'widget_taxonomies');
    
    function widget_taxonomies(){
    
      $labels = array(
        'name' => _x( 'Brands', 'taxonomy general name' ),
        'singular_name' => _x( 'Brand', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Brands' ),
        'all_items' => __( 'All Brands' ),
        'parent_item' => __( 'Parent Brand' ),
        'parent_item_colon' => __( 'Parent Brand:' ),
        'edit_item' => __( 'Edit Brand' ), 
        'update_item' => __( 'Update Brand' ),
        'add_new_item' => __( 'Add New Brand' ),
        'new_item_name' => __( 'New Genre Brand' ),
      );
    
      $args = array(
        'labels' => $labels,
        'hierarchical' => false,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'brand' ),
      );
      
      register_taxonomy('brand', 'widget', $args);
    }
    

    You will notice that hierarchical is set to false so this means this custom taxonomy will be function like a tag. In the admin panel the first thing to notice is a new link in our widget tab that links to out brand manager:

    Example image of a complete use of a custom taxonomy

    If you are on the edit/add widget pages you will see this:

    edit page example of custom taxonomy

    You see that it is acting like the tags in the normal post screen. Lastly, lets take a look at the classification on the front end:

    You can see we can find a list of widgets under this URL.

    Pretty simple method to adding your own classifications. This combine with the custom post type makes the wordpress 3.0 version very powerful. Next we will look creating a class to create custom post types and custom taxonomies.

    SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
    Posted in Development | Tagged | Leave a comment

    Simple But Great Function home_url()

    home_url() is a new function added to 3.0 version of WordPress. It template function that allows you to create URL’s that begin with your home address. Home_url() might sound complicated but it is extremely easy to use and will make your coding simpler. Lets take a look at the function:

    <?php home_url('path', 'scheme');?>

    As you see above the function takes two arguments:

    Path – This is an option argument that allows you to create a custom URL using this path. Lets say you have a page with the slug “about” which represents the page you have titled “About”. You can pass “about” as the path and it you create the following URL: http://www.yoursitesaddress.com/about.

    Scheme – This is an optional argument. This allows you to determine whether “http” or “https” will be used at the beginning of the URL.

    Things to know about the home_url() function

    1. It will automatically use http or https depending on the options you have for the site. This will allow not to worry about having protocol, WordPress will know.
    2. If you don’t pass in a path, then the default will be the site’s URL. This will make the use of get_option(‘home’) or bloginfo(‘home’); very limited.
    3. The use of the home_url() function will make your template and plugin design universal. But this function will not be recognized by older versions of WordPress.

    Example using the home_url function

    Here is in use to create a path to one of my older posts.

    <?php home_url("using-custom-fields");?>

    This will return the following URL: http://www.wpinsideout.com/using-custom-fields

    That is really it. It is almost to simple but knowing this function will allow you to create URL’s quickly and the URL’s you create will universal. And by universal meaning, if you launch a site using a theme you were developing on your own computer, the URL’s will automatically change from your own computers home address to the address of your new site.

    SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
    Posted in functions | Tagged | Leave a comment