WordPress

Adding Custom Information to WordPress Posts

In this article I’m going to show how to add custom information to your WordPress posts. We’ll start with the standard custom fields, very useful if you’re the theme developer and the only blogger. Next I’ll show you how to create your additional fields. They’re work pretty much like the custom fields, but you can add a name and description to them, so your theme users know what to write there. The last thing I’m going to show is the custom taxonomies added in WordPress 3.0.

Custom Fields

The WordPress custom fields allows you to add different information to your post. When you use them you are able to place these fields directly in your theme template and give a standard look to your posts even when you have different bloggers. In the past this feature was used to add post thumbnails, but today we can use the Featured Image. But we can use it for different information like, for example, the difficulty level of your tutorial post.

There are two ways of doing this: the standard one and the customized one.

Standard Custom Fields

The standard way of using custom fields are really simple. When you add a new post, you can see after the Excerpt and Send Trackbacks areas a area called Custom Fields. It looks like this:

Standard Custom Fields

Standard Custom Fields

As you can see, you’re able to add as many fields as you want. You just have to name them and set their value. Then you may add them to you theme template by using the function get_post_meta($post_id, $key, $single). Here is an example for the difficulty level of your tutorial:

<?php if ( get_post_meta($post->ID, 'difficulty', true) ) : ?>
        Difficulty: <?php echo get_post_meta($post->ID, 'difficulty', true); ?>
<?php endif; ?>

But you can make it simpler to your blog’s user.

Predefined Custom Fields

In your theme’s functions.php file you are able to predefine which are the custom fields you want for your theme. You have different ways to implement this, so I’ll show here one way of doing it. So open your theme’s functions.php file and do the following steps.

Step 1 – Field Definition

We start by defining what fields we’ll have. We can do that by creating a array with the details of each field. Here I’m going to create two fields, the difficulty level and a screen cast link (using the YouTube video ID).

    $theme_metaboxes = array(
       "difficulty" => array (
            "name"      => "difficulty",
            "default"   => "3",
            "label"     => __('Tutorial Difficulty Level', 'mytheme'),
            "type"      => "text",
            "desc"      => __('Enter the difficulty level here. Use only integer numbers from 0 (zero) to 5 (five).', 'mytheme')
        ),
       "screencast" => array (
            "name"      => "screencast",
            "default"   => "",
            "label"     => __('YouTube Screencast', 'mytheme'),
            "type"      => "text",
            "desc"      => __('Enter the YouTube ID here. For example: http://www.youtube.com/watch?v=SuNprTu5Y5c, use only the "SuNprTu5Y5c" value. Use the original studio trailer if possible.', 'mytheme')
        )
    );

As you can see we defined the following values for each field:

  • name: field name;
  • default: value that should be used as default;
  • label: name that is displayed to the user;
  • type: type of the HTML input field;
  • desc: description shown after the field entry.

Step 2 – Add the Fields to the New Post Page

Now we need to add the necessary HTML to the WordPress New Post page. We’re going to create two new functions and use a new action hook. Here is the code:

    function custom_fields_box_content() {
            global $post, $theme_metaboxes;
            foreach ($theme_metaboxes as $theme_metabox) {
                    $theme_metaboxvalue = get_post_meta($post->ID,$theme_metabox["name"],true);
                    if ($theme_metaboxvalue == "" || !isset($theme_metaboxvalue)) {
                            $theme_metaboxvalue = $theme_metabox['default'];
                    }
                    echo "\t".'<p>';
                    echo "\t\t".'<label for="'.$theme_metabox['name'].'" style="font-weight:bold; ">'.$theme_metabox['label'].':</label>'."\n";
                    echo "\t\t".'<input type="'.$theme_metabox['type'].'" value="'.$theme_metaboxvalue.'" name="'.$theme_metabox["name"].'" id="'.$theme_metabox['name'].'"/><br/>'."\n";
                    echo "\t\t".$theme_metabox['desc'].'</p>'."\n";
            }
    }

    function custom_fields_box() {
            if ( function_exists('add_meta_box') ) {
                    add_meta_box('theme-settings',__('Custom Settings', 'mytheme'),'custom_fields_box_content','post','normal','high');
            }
    }

    add_action('admin_menu', 'custom_fields_box');

In this code we use our array with fields to create the necessary HTML to be used in our admin area, when we create a new post. The result is this:

Improved Custom Fields

Improved Custom Fields

Much more user friendly, don’t you think?

Step 3 – Using the Values

The last part is the actual value usage. We need another action hook to add/update/delete our values. So we’ll create another function like this:

    function custom_fields_insert($pID) {
        global $theme_metaboxes;
        foreach ($theme_metaboxes as $theme_metabox) {
            $var = $theme_metabox["name"];
            if (isset($_POST[$var])) {
                if( get_post_meta( $pID, $theme_metabox["name"] ) == "" )
                    add_post_meta($pID, $theme_metabox["name"], $_POST[$var], true );
                elseif($_POST[$var] != get_post_meta($pID, $theme_metabox["name"], true))
                    update_post_meta($pID, $theme_metabox["name"], $_POST[$var]);
                elseif($_POST[$var] == "")
                    delete_post_meta($pID, $theme_metabox["name"], get_post_meta($pID, $theme_metabox["name"], true));
            }
        }
    }

    add_action('wp_insert_post', 'custom_fields_insert');

As you can see we use the WordPress functions to add, update and delete the values according to the fields we’ve created.

In order to use these fields, you can do the same as we did for the standard WordPress custom fields. You can create a new function for that as well. For example, in our screen cast example we could create a function that would show the video only if the user set the value:

function screen_cast($id) {
    if ($id) {
        echo '<div class="youtube">'.
             '<object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/'.$id.
             '?fs=1&amp;hl=pt_BR"></param>'.
             '<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>'.
             '<embed src="http://www.youtube.com/v/'.$id.'?fs=1&amp;hl=pt_BR" type="application/x-shockwave-flash" '.
             'allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object>'.
             '</div>';
    }
}

With this function we can add a simple function call to our single.php template:

        <?php screen_cast(get_post_meta($post->ID, 'screencast', true)); ?>

And that’s all we need to use custom fields!

Custom Taxonomies

The last thing I’m going to show is the custom taxonomies feature added in WordPress 3.0. This is a powerful feature and is really simple to be used. They work just like post tags so you’re able to use as much values as you want. All you need is a new function and a new action hook in your functions.php file. In the next example I’m adding the custom taxonomy for a list of actors. The necessary code is:

    function create_custom_taxonomies() {
        register_taxonomy('actor', 'post', array(
            'hierarchical' => false, 'label' => __('Actor(s)', 'mytheme'),
            'query_var' => true, 'rewrite' => true));
    }
    add_action('init', 'create_custom_taxonomies', 0);

And that’s it. It’s really simple. This is the result:

Custom Taxonomy

Custom Taxonomy

In order to show the values in your single.php template, this is what you need:

                <?php echo get_the_term_list($post->ID, 'actor', __('<p>Actor(s): ', 'mytheme'), ', ', '</p>'); ?>

Conclusion

In this article I showed how to use Custom Fields and Custom Taxonomies. These two “features” let you customize your blog posts and make them unique. Besides, they help you improve WordPress usability by separating information in different fields.


  • Sergio

    Great explanation on how to put it altogether and the pics make it easier to understand what the coding does. Thanks for the great article.

  • Pingback: What I’m Reading (weekly) | tj mapes()

  • Thanks for this post. I m finding it

  • MIchael

    Thank you for the post. Having issues with execution. I have followed the first 3 steps with no problems. Changed the Values to reflect my needs ( I am setting up an products page). But you lost me on the final step. Your example is to set to ECHO a youtube video. In my case I my fields are simply text description. What code would I use for that? Thanks.

    • In your case you can simply use echo get_post_meta($post->ID, ‘difficulty’, true); It will return the value inside you custom field. Cheers

  • Thank you. This is showing up for a new post, but what if I want to add this to my custom post type posts?

  • After going over a handful of the blog posts on your web site, I seriously appreciate your way of blogging. I saved it to my bookmark site list and will be checking back in the near future. Take a look at my website as well and tell me what you think.