Today’s Basix video quick tip topic comes from a question on Twitter, concerning the use of custom fields in WordPress. Luckily, as you’ll find, attaching unique data to postings is as simple as assigning a value in the “Edit Post” page, and then referencing that information with the get_post_meta() method.
Prefer to watch this video on Screenr.com?
Step 1: Create a New Post
In your local testing environment, create a new posting in the WordPress admin panel, and scroll to the bottom, until you see the “Custom Fields” widget.
This section allows for a key, and a value. For example, if you aren’t taking advantage of the new “Post Thumbnail” feature, available in WordPress 2.9, and need a way to attach a thumbnail to each posting, this is where you’d accomplish that task. You could assign a key of “thumb,” and a value, which is equal to a path to the desired thumbnail. Go ahead and fill this section with some test data – anything you wish. I’ll use “difficulty” as my key,” and “hard” as the value.
Step 2: Edit Index.php
Now visit your theme, and within the WordPress loop in your index.php page, reference the get_post_meta() method.
<?php echo get_post_meta($post->ID, 'difficulty', true); ?><
This method accepts three parameters.
- The id for the desired post. You can use $post->ID or “the_id()” to insert this value.
- The key that you require. Remember, you can insert multiple custom fields. This is why we need to reference the key, in my case, “difficulty.”
- A boolean, which determines whether you want the information returned as a string, or an array. As I’m echoing out my value, I’ve chosen true (or string).
Step 3: What If…
If you view run the website, you’ll see the correct value. If you went with a thumbnail path in your custom field, make sure that you echo out that string from within an IMG tag, accordingly. However, there’s one problem here; it’s possible that not EVERY single post will have this “difficulty” custom field attached, yet we’re blatantly assuming that there will be. This is inefficient. Instead, why don’t we first create an “if” statement, and determine whether our desired key exists first. Smarter right?
<?php if ( get_post_meta($post->ID, 'difficulty') ) : ?> <small> <?php echo get_post_meta($post->ID, 'difficulty', true); ?></small> <?php endif; ?>
Custom fields are a staple in every experienced WordPress designer’s toolbox. Learn them, and use them! Thanks for reading or watching!