Site icon DsgnWrks

Post Meta.. How do I save it?

This is Part 2 of a five-part series on working with WordPress post-meta. If you haven’t, you’ll probably want to start with Part 1.

Today, we’re going to talk about how to store those bits of data
to your posts, pages, or even custom post types. As mentioned in the
previous article, there are two primary WordPress functions for updating
and adding post meta, update_post_meta and add_post_meta, respectively.

Let’s look at a few examples of data that we want to store to post meta:

If you recall, by default, post meta expects to be stored as an
array which would contain multiple rows data. However, in most cases, we
only want to store one piece of information for each post meta key. So
for the first three examples, we’ll want to use update_post_meta, as it will overwrite any existing values with a new value for that key. We’ll then make sure we pass that third parameter in get_post_meta to retrieve just the one value. Let’s look at some code:

$post_id = 25;
$meta_key = 'wpsnipp_post_background_color';
$meta_value = '#f00'; // red
update_post_meta( $post_id, $meta_key, $meta_value );

// ... Later in your theme or plugin

// Let's retrieve our color value
$color = get_post_meta( $post_id, $meta_key, true );

That’s it.. Whenever this code runs, it will update the post
meta, and we’ll be able to grab it anywhere else in our plugin or theme
via this snippet:

$post_id = 25;
$meta_key = 'wpsnipp_post_background_color';
// Let's retrieve our color value
$color = get_post_meta( $post_id, $meta_key, true );

Let’s go ahead and update our next 2 meta data values.

$post_id = 25;
// Update our subtitle
$meta_value = 'The Greatest Post Ever Written';
update_post_meta( $post_id, 'wpsnipp_post_subtitle', $meta_value );

// Update our "show social links?" meta
// We could save this as true or false
update_post_meta( $post_id, 'wpsnipp_show_social', true );

So we’re almost there. We’ve saved 3 pieces of related meta data
to our post that we can use in our templates to give them a custom feel.
Since our last bit of post-meta, “Extra Resource links” will most
likely take multiple resource urls, we’ll save it for our next post
describing the use of add_post_meta.

We wanted to keep these posts to the basics of working with post
meta, but we have left out one crucial detail, that of sanitization.
Anytime you’re adding data to the WordPress database, you want to take
precautions that the data is safe. WordPress has provided us with no
shortage of functions that can help you sanitize data before saving it (sanitize_text_field, sanitize_email, wp_kses_post, etc).

Part 2 of a 5 part series originally written for wpsnipp.com (1, 2, 3, 4, 5)

Exit mobile version