WordPress Custom Fields [ Part 1 ]
What are WordPress Custom Fields?
Custom fields are a form of meta-data to store arbitrary information with each post of WordPress. While this does not sound so powerful, it is the most powerful of the WordPress posts and content types (type known as post). This meta-data is handled with key / value pairs. The key is a “name” that identifies the specific field so it is a constant and must remain the same for all messages however you can use the same key several times in one post. The value is the information to be displayed for the field when you do on your WordPress theme so you can change with each message.
Now let’s look at a very basic example of WordPress Custom Fields in Action. When editing messages, you see the section called Custom Fields. Scroll down a bit, and you should see one. We will use the box to add the author’s mood since the time of writing. As you add the name of “mood today,” and then adds the value that can be happy, so sad, excited etc.
Now once you add this field, and save the message. This additional information related to the arbitrary message is stored in the database, and can be called from anywhere within your WordPress theme. So for this example is very simple, we will use the very basic form of display in the message. Say, you want to display your mood before the person reads the message, so they know what to expect. Well, then open the single.php file and add this code inside the WordPress loop:
It will display something like this:
Today’s Mood: Happy
Now by using the_meta hook, you will display all fields associated with that post. This is great when you have one field, but if you have 5 different fields that you want to display at 5 different locations, then we will have to use get_post_meta hook. Let’s say you want to display the custom field at a separate location by itself, then you will add the following code within the post loop.
ID, 'key', true); ?>
Note: replace the key value to whatever your key is.
What if you have a custom field like ‘songs’ for the songs you were listening while writing the post? Well you can have multiple ‘songs’ keys and have different values stored from the backend. Then inside your loop paste a code like this:
ID, 'songs', false); ?>
This post is inspired by:
Note the trick here is the third parameter “false”. By changing to false, we tell the function to return an array of values for the specified key. This is a useful tip for viewing multiple key values.
Source: Jeff Starr at Perishable
How to Hide Custom Fields from Your Users
Open up your theme’s functions.php file and add the following:
add_action('admin_init','remove_custom_meta_boxes'); function remove_custom_meta_boxes() { remove_meta_box('postcustom','post','normal'); remove_meta_box('postcustom','page','normal'); }