Using Custom Fields

If you are unfamiliar with custom fields, you need to be. What custom fields is to allow you a way to store bits of data that you need to associate with a post. This data is sometimes called meta data and has numerous uses.

Adding Your Own Custom Fields in the Admin

To really understand how custom post functions you need to first look at the custom post fields on the post or page screens in the admin. When you are on the add or edit screen towards the bottom you will find this:

Using this interface you can being to add custom fields.  My idea is that you are writing posts about countries and every post you want some way to store the location of a map that you have uploaded related to the post.  In this case, you will need to give the name “map” and paste the location of the map in the value.  Here is the custom field filled out.

You just need to hit add custom field and the field will be added.

You added the Custom Field Now What

The custom field has been added in the admin but when you visit the post, you notice that there is no change.  The reason is we need to retrieve this information to display it.  To do this we are going to have to modify our single.php file in our active template.  So I am going to open up my single.php file and add some code:

<?php
  $map = get_post_meta(get_the_ID(), 'map', TRUE);
  if(!empty($map)):
?>
<img src="<?php echo $map;?>" alt="My Map" />

<?php endif;?>

First, you will see that we used the function get_post_meta(). This function accepts a few arguments:

  • Post ID – This is the post id of the post. In this example, we are using the function get_the_ID() to get the current ID of the post.
  • Custom Field Name – this is the name that we gave the custom field in post edit page. This is require because we could have several custom fields for this post so this acts as a index to pull out the information we want.
  • Single – This is a boolean (True/False), which indicates that we want this specific value. If you do not include this an associated array will be returned with the information. By stating that it is single, WordPress will just return that single value.

We also took that value we got with the function and put in a variable. We then tested it using the empty function with a exclamation to indicate the opposite as to say if $map is not empty then do something. We then use a ternary operator, the colon. Then we use an image tag with the $map variable to echo the image. We then end the statement with the endif;. So lets see what that gives us.

custom field tutorial

So if we visit our other posts that don’t have a map custom field, they will show nothing. Pretty slick.

Other Applications

Hopefully this custom post tutorial opened your eyes to the ease and power of custom fields.  They are great for creating custom home pages where you have different sections of content which would normally fit in the post area.  So many you have a box on your home page that gives a sentence or two about your services, storing this is a custom field makes it super easy to manage.  Also, instead of maybe your client having to ask you to edit html to change text, he or she can go to the page and edit the custom field and bam the change is made.

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

Your Own Custom Post Types

There is an exciting upgrade to WordPress that makes it a more versatile content management system called custom post types.  To better understand what a custom post type is, the most common example used is to create a post type for books.  The post type would be book and each new post created would represent a different book.  Also, in the admin panel there would a tab for this post type with the same function as current post and page tabs for adding, editing, categorizing, tagging, and deleting this post type. Sounds great right and the application seems limitless.

Background on What is a Post Type

In the older versions there was only a few post type that WordPress would use.  Here is the breakdown with a description of each:

  • Post – This represents the published content of a blog in the form of posts.  Each row in the database assigned with this designation could be found under the posts tab in the admin.
  • Page – This is the also represents published content within the site and each row in the database with this designation would be found in the admin under the page tab
  • Attachment – This post type represents and file that has been uploaded to WordPress.  A perfect example is an image you add to a post.  This would be uploaded into the posts database and give the post type designation of attachment.
  • Revision – This represents a older revision of a page or post.   Every time you update a post or page a revision is created with the old data.  This provides you a method to restore posts to their old content if needed.  Post and page revisions are found on the edit post and edit page screens towards the bottom.  Each revision shown here represents a row in the posts database.
  • Draft/Auto Draft – These could be a few things.  The first would be when you don’t actually publish a page or post and just hit save draft.  The next would be a auto save that is done by WordPress as you are editing a post or page.

How the new Post Types Work

Seeing above that there was only a few was to class content, the new version allows you to create any post type that you want.  As example, you can have post types that represent products, books, real estate listings, or whatever else you can think of.

When you create a new post type you will have the benefit of all the cool options on the post and page screen.  Also, you will be able to create your own custom meta boxes to have custom areas of content.  An example of this would be a field that you can enter the price of a product.

How to Use Custom Post Types

We basically have two options of where we want to create our new custom post type. The first would be in our function.php file in our theme and the second would be in a plugin file that we create. For this tutorial, we are just going to use our function.php file located in our active theme.

Next we are going to have to hook onto the initialization of WordPress and then use a function to register the post type. The frame of the code will look like this:


add_action("init", "add_my_post_type");

function add_my_post_type(){
    register_post_type("my custom post type", $options_array);
}

Again we are using the add action function to hook onto the initialization process of WordPress and when WordPress initializes it will trigger our function to run to register our new custom post type.  There are a few options that you should be familiar with:

  • labels – This is an array that WordPress will use to apply names to the different inputs and names throughout the admin.  So instead of add post, you would see “add book”.  The way to assign what and where labels will be used by WordPress is by creating an associated array and using this in the options array.  See the code below to see it in action.
  • publicly_queryable - this is a boolean (true or false) that will indicate whether your custom post will be include in search results.
  • query_var - this is a boolean as well that determines how these custom post will be designated in the URL of your site.  So if you have a custom post type for products, to view a product you will need to put in the following URL: http://www.yoursite.com/product/your-product-name.
  • rewrite – This is a boolean which tells wordpress if you are using a custom link structure like the one above.
  • hierarchical – This option is a boolean.  A true here will indicate that your custom post type can have parents and children.  In this case they will be functioning like pages.  False means that they will not have the ability to have parent and children.
  • supports – This is an array of the type of meta boxes that you will have in your custom post type.  The editor represents the content editor that you would find in the post or page edit or add pages.   And so forth.

Here is it in action, the post type we have added is called “widget”.

 
  add_action('init', 'my_widget_post_type_init');

  function my_widget_post_type_init()
  {
    $labels = array(
      'name' => _x('Widgets', 'post type general name'),
      'singular_name' => _x('Widget', 'post type singular name'),
      'add_new' => _x('Add Widget', 'book'),
      'add_new_item' => __('Add New Widget'),
      'edit_item' => __('Edit Widget'),
      'new_item' => __('New Widget'),
      'view_item' => __('View Widget'),
      'search_items' => __('Search Widgets'),
      'not_found' =>  __('No Widgets Found'),
      'not_found_in_trash' => __('No Widgets 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('widget',$options);
  }

As you will see this will add the tab in the admin for custom the custom post type widget.

Adding a custom post type in wordpress

So our custom post type exists and we can just start adding content, but we really should address the message that WordPress outputs when we add, edit, and delete a post (there are more).  So we are going to use a filter hook to filter the WordPress messages to add our own to be used with our custom post type. Here is how we do it.

add_filter('post_updated_messages', 'widget_messages');
  
  function widget_messages( $messages ) {
   
    $messages['widget'] = array(
    0 => '', 
    1 => sprintf( __('Widget updated. <a href="%s">View Widget</a>'), esc_url( get_permalink($post_ID) ) ),
    2 => __('Custom field updated.'),
    3 => __('Custom field deleted.'),
    4 => __('Widget updated.'),
    5 => isset($_GET['revision']) ? sprintf( __('Widget restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
    6 => sprintf( __('Widget published. <a href="%s">View Widget</a>'), esc_url( get_permalink($post_ID) ) ),
    7 => __('Book saved.'),
    8 => sprintf( __('Widget submitted. <a target="_blank" href="%s">Preview widget</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    9 => sprintf( __('Widget scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview book</a>'),
      date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
    10 => sprintf( __('Widget draft updated. <a target="_blank" href="%s">Preview widget</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    );
   
    return $messages;
  }


Now when you add a post you will see this:

Custom Post Messages

You see some nice text that indicates that your custom post type has been modified depending on your action.

Now that you see how easy it is to you can start to add your own. In the future we will cover how to add custom meta boxes to the custom post pages. How to save these custom meta boxes and lots of other cool stuff like add JavaScript to your custom post pages to add some usability.

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

The Beginning Steps to Writing Your Own WordPress Plugin

The beauty of WordPress is its ability to be customized.  The plugin API provided by WordPress is extremely extensive and having knowledge of how to create your own plugins will allow to take your development to the next level.

Creating Your Folders and Files

When creating your first plugin, you will need to put the files in the WordPress plugins directory.  If it is a simple plugin, say only one PHP file, you can put it directly inside the folder, but as you build more complex plugins, it is best to put all your files inside a folder in this directory.  After you have all your files in one folder you should have one PHP file that is the main plugin file with a name similar to the folder it lives in.  Also, if you have multiple files like CSS, javascript, or whatever else, it is a best practice to have these in their own folders inside your main plugin folder.  This helps to keep the workspace clean and could save you time down the road.

The naming of you plugin should be a unique one.  First, if you have the same name as another there could be a potential conflict.  Second, if you want to upload your plugin to the WordPress repository of plugins, you can use a name that is already taken.

Your first plugin file

When you create your folder to contain your plugin, WordPress won’t register it as a plugin until you add your main plugin file.  This is a PHP file that WordPress will recognize and upon activation will add your custom functionality. Inside that file, we must start it off with a bit of custom syntax to have WordPress recognize it as a plugin.  See below.


<?php
/*
Plugin Name: My New Plugin
Plugin URI: This is the URI of your plugin
Author : Your Name
Author URI : Your website
Description:  Your plugin’s description
Version: The version of your plugin
License: What license does it adhere to
?>

After that you add those few lines of code, your plugin will show up on WordPress’ plugin page and you can activate it.  But since you have no functions yet, it won’t do anything.  So what now?  How do we get it do something.  We need to have some custom function that fire are certain points and we to “hook” onto these point to make the work.

An Explanation of Hooks

Again back to the WordPress’ ability to be customized.  Hooks are going to be what you use to add your own functionality.  To make your plugin to work, you must use a hook to set your plugin into motion.  There are two types of hooks and you should know how each work before moving forward with your plugin.

Action Hooks

An action hook is an event that your plugin can hook onto.  They happen a specific times and hooking onto them will cause you plugin to fire at that time as well.  To hook onto an action hook in your plugin you must call the add action function listed below.


<?php add_action(‘action hook name’, “your function”, $priority, $accept_args );?>

Here is a breakdown of the parameters for this function:

Action hook name – this is the name of the hook you are hooking onto.

Your Function – is the name of the custom function that you create to fire when this action hook is executed.  So if function is to email you when someone accesses your site, you could have a function that sends an email when the wp_head is loading.

$priority (optional) – this gives you the ability to select the order to which wordpress will execute your custom function.  A better way to understand this is to say we have two plugins that hook into the same action.  Well WordPress can be told which one should happen first and setting the priority will give you this ability.

$accept_args (optionial) – This is integer for how many arguments your custom function will require.

Here is an example of this where we use the wp_head hook to add a JavaScript file to the head of our document.


add_action(‘wp_head’, ‘add_my_javascript’);

function add_my_javascript(){
  echo "http://PathToMyJavaScript";
}

If you added this would find that your statement was echo when the wp_head() function was executed in the head of your theme.  Maybe this not the best way to add JavaScript to your head but that is a later post.

Filter Hooks

You should think of these hooks as a means to modify content being read from or written to a database.  An example of this would be the changing the content excerpt.  You would hook onto the excerpt pass it through you PHP function and it would then be returned out to the visitor.   The function you will use to add a filter is listed below:


&lt;?php add_action(‘filter hook name’, “your function”, $priority, $accept_args );?&gt;

Filter hook name – this is the name of the hook that you want to apply your filter function to.

Your Function – This is the function that you will use to modify the content.

$priority (optional) – Is the order in which your function will be carried out.  Same as above for the add_action function

$accept_args (optionial) – This is integer for how many arguments your custom function will require.

An example would be to limit the length of site’s excerpt.  The standard excerpt is 55 words long but you can limit this be using your own custom function and applying this function to a filter hook.


add_filter(‘excerpt_lenght’, ‘my_new_excerpt_length’);

function my_new_excerpt_length($length){
  return 30;
}

This is all you need to do to change the length of the excerpt from 55 words to 30 words.  But lets look at one thing that might trip you up.  The addition of the parameter $length to the custom function.  This is the thing you are filtering.  When you are modifying content using a filter hook, you function needs to accept the content that you are filtering so in this case it was the length of the excerpt.

Looking for a hook

Here are several good resources for hooks.  The first being Adam Brown’s database of hooks, which at the time of this writing has 1344 hook listed.  The other two are lists of hooks on the wordpress.org site.

Going Deeper Into Plugin Development

The more you use the plugin API the better you will become at creating plugins.  From my own experience many individuals out there can slice and dice a theme, but sometimes these same individuals lack the knowledge of how to create plugins and custom functionality.  You will immediately standout as an expert if you know how to create plugins and will become a relied upon asset for many people.

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