Using A Custom Field In WordPress – An Example

Wordpress Custom Fields

Custom fields in WordPress seemed like an elusive topic. For quite a while, whenever I needed to include something in my theme that didn’t have a place within the WordPress admin interface, I would hard code variables into the PHP. That was entirely more work that was necessary. I finally realized the simplicity and power of custom fields. I thought I’d share my most recent use of a custom field with the thought that a simple example may make it easier for the next guy.

My theme was to be used for a blog involving a large number of authors and I wanted to include the author’s name in the same place within the theme for each post. Here’s the part I added to the theme where I wanted to display the author’s name. (within PHP tags of course)

$myauthor = get_post_meta($post->ID, $key, true);
if (!empty($myauthor)) {
echo “<div class=\”postauthor\”>by “.$myauthor.”</div>”;

After you’ve added something like this to your theme, just go to your new post and add a custom field with the name that you put here that is fed into the $key variable. Then enter a name for the post’s author.
I’ve added a css class to the div so we can style it to fit the theme.

All of this can be altered to fit other uses of course. If you’d rather use the field to display the name of a song that inspired your post, or the book you’re currently reading, just change the name in the custom field on your post and in your theme, change the “Post_Author” to whatever name you chose for your field.

I am aware that for blogs with more than one user, the post author field will be available to select the posts author from the list of users. That’s great but makes a far less useful example of how to use custom fields.

This article has 1 comments