Add a User Interface to WordPress Custom Fields

Custom fields are great for adding additional functionality into WordPress sites. I have used them in the past to set up post thumbnails, for music album metadata, such as artists and album year, to set articles to link to their original sources, and many others.

The problem is, the default interface for adding custom fields is very clunky. The user has to either manually type in the field name, or select it from a list.

This doesn’t work too well for an average client. The reason I use WordPress on my sites in the first place is for ease of use. Fortunately, there’s an easy way to use custom input boxes! Simply paste the code below into your theme’s “functions.php” file, adjust the variables, and you’re good to go!

/* add actions to admin menu */

add_action('admin_menu', 'fieldname_add_custom_box');



/* use save_post action to handle data entered */

add_action('save_post', 'fieldname_save_postdata');



/* Adds a custom section to the "side" of the post edit screen */

function fieldname_add_custom_box() {

    if(function_exists('add_meta_box')) {

	add_meta_box('fieldname', 'fieldname', 'fieldname_custom_box', 'page', 'normal', 'high');

    }

}



/* prints the custom field in the new custom post section */

function fieldname_custom_box() {

    //get post meta value

    global $post;

    $fieldname = get_post_meta($post->ID,'fieldname',true);



    // use nonce for verification

    echo '';



    // The actual fields for data entry

    echo '
Label
'; echo 'Label:'; echo ''; echo '

Description of what this field does.

'; } /* when the post is saved, save the custom data */ function fieldname_save_postdata($post_id) { // verify this with nonce because save_post can be triggered at other times if (!wp_verify_nonce($_POST['fieldname_noncename'], 'fieldname')) return $post_id; // do not save if this is an auto save routine if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id; $fieldname = $_POST['fieldname']; update_post_meta($post_id, 'fieldname', $fieldname); }

Go in there and replace fieldname with the name of your custom field, and fill in Label and the description and save your file. You can also add multiple fields into one option group. If you want this box to show up on posts instead of pages, change “page” to “post” in the arguments for add_meta_box().

This is what the new field looks like when setup on a site. This box lives just below the main entry area. You can adjust the options in add_meta_box() to change the placement on the page. I hope this helps you improve the usability on your WordPress site!