Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 6 • Advanced Theme Usage 141


Figure 6-2: The Custom Fields box resides on the Add New Post screen, underneath the regular post-writing box — don’t
forget to enable it if needed!


Custom fields are actually metadata, but they are called custom fields within the WordPress
admin interface. Most of the time, metadata belongs to posts and consists of two things: a key
and a value. You can add new keys whenever you want, and after you’ve used them once, they
show up in a drop-down box, which is nice because you may misspell or forget about them
otherwise. Metadata can also belong to comments and users.


CUSTOM FIELD BASICS


Getting started with custom fields is easy; just write a post and add something in the key field
and then something in the value field, and click the Add Custom Field button to save. You’ve
now stored your custom field data, although it won’t show up anywhere unless you call it
within a template file. The idea is to reuse the key across posts, in a way like a categorization
of the kind of data you’re storing, and just alter the value.


The template tag you use to make things happen with custom fields is the_meta(). By
default, it outputs an unordered list (or a ul tag with list items, lis, in HTML speak)
displaying the post’s custom fields. That works great if you just store things such as how happy
you are and what you’re reading right now, or perhaps a grade for a review or something. The
ul will have the class post-meta, and then there’s an li for each custom field; within this
li there is a span with class="post-meta-key" that wraps around the key for that
particular custom field. After that is the value in plain text.

Free download pdf