DsgnWrks

  • Home
  • Code
    • Plugins
      • BibleGateway Links Shortcode
      • CMB2
      • Code Snippets CPT
      • Cubify WP
      • DsgnWrks Importer for Instagram
      • Easy Digital Downloads – Internal Notes for Products
      • DsgnWrks Twitter Importer
      • Enhanced Admin Bar with Codex Search – WordPress Plugin
      • Google Analytics Top Content Widget – WordPress Plugin
      • Hash Link Scroll Offset
      • HTML5 Slideshow Presentation – WordPress Plugin
      • IFTTT Post Formats
      • Jetpack Slideshow Caption
      • Network Sites Counts Dashboard Widget
      • story|ftw
    • All projects
  • Talks
  • Connect
  • About

1 Comment

Posted on September 28, 2015

Post Meta.. How do I save it? (add_post_meta)

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

  • Post background color: #FF0000
  • Subtitle: My Post Subtitle
  • Show Social Links?: true
  • Extra Resource links: Multiple URLs

We managed to accomplish our task of saving the data for the first three using the handy WordPress-provided function, update_post_meta. However, for the last bit of data, we want to store that data in a slightly different way.

Since we want the ability to store multiple URLs for one post meta key, we’ll use the function add_post_meta instead. As suspected, this function allows us to continually add more entries to the post meta field.
Let’s dive in to code:

$post_id = 25;
$meta_key = 'wpsnipp_post_extra_resource_links';
// Add one resource
$meta_value = 'http://google.com';
add_post_meta( $post_id, $meta_key, $meta_value );

// And another
$meta_value = 'http://amazon.com';
add_post_meta( $post_id, $meta_key, $meta_value );

// No resource list would be complete without wpsnipp.com
$meta_value = 'http://wpsnipp.com';
add_post_meta( $post_id, $meta_key, $meta_value );

Ok! Hopefully it’s obvious what we’ve accomplished, but let’s review. First we set up our $post_id and $meta_key variables. We created these variables first because they’ll be re-used for each add_post_meta call.

Next, we add 3 different values to our post meta field. So that’s
great, but how do we retrieve those values and verify that it’s all
working. If we used get_post_meta( $post_id, $meta_key, true ); like in our last example, what do you think would be the result? Well,
we would just get the first row’s value, ‘http://google.com’. Obviously,
that was not our intention, but rather to retrieve a list of resources
that we could then display in our theme, possibly in an unordered list
in our sidebar, or below the content. So let’s make that happen.

// ... Later in your theme or plugin
// This retrieves current ID if we're in the loop
$post_id = get_the_ID();
$meta_key = 'wpsnipp_post_extra_resource_links';

// Now, let's retrieve our list of resources
$resources = get_post_meta( $post_id, $meta_key );

Notice that the third parameter is ommitted. That’s because the third parameter in get_post_meta is set to ‘false’ by default, so since that is what we want, we can simply ommit the last parameter.

This will then return an ‘array’ of resources. If you’re not familiar
with arrays, just know that it is the list that we are looking for, and
we will need to iterate over that list via a loop, a term you have
undoubtedly heard, most often in reference to the WordPress posts loop.
For our use-case we will use a foreach loop, which simply
means, for each item in our list (array), do the following (followed by
your code). So we’ll do exactly that, loop through the resources and
create an unordered list.

// Let's make sure we have some resources before we start
if ( $resources ) {
    ?>
    <ul class="extra-resources">
    <?php
    foreach ( $resources as $link ) {
        ?>
        <li><a href="<?php echo esc_url( $link ); ?>"><?php echo esc_html( $link ); ?></a></li>
        <?php
    }
    ?>
    </ul>
    <?php
}

Let’s review. We first grabbed our list of resources by using get_post_meta,
and ommitting the third parameter. We then checked to verify that we
did, in fact, have some resources. We did this because there is no sense
in outputting an empy <ul></ul> tag if we don’t have any list items to fill it with. Inside our conditional, we have output the opening <ul> tag and begun our loop. As the foreach loop iterates across the array, it places each item into a variable we called $link. We then ouput our link tag, <a href=… wrapped in the <li> tags.

In the last article, I mentioned the importance of sanitization.
Sanitization is the act of cleaning our data before input, or saving it
to the database. Another equally important aspect of passing around
data, is the act of “Escaping” or cleaning our data before output. In the above example, I have used 2 functions which WordPress provides to help escape our data before display, esc_url, and esc_html. The former, esc_url is self-explanatory in that it makes sure the data being shown is a
proper url, and even verifies that the ‘http://’ is attached to the
beginning. The second, esc_html removes any html in the
data being displayed. In our case, we’re just displaying the url, so we
know we don’t want any html tags in there.

Ok, so it’s that easy to save multiple sources of information to the
same meta key and then to display it. There are some other caveats to
working with arrays of data and the post meta functions, but we’ll save
those for another article some other time. What kinds of data will you
be saving and displaying?

In the next article, we’ll walk you through a simple example of saving post meta data each time a post is saved.

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

Share the love:

  • Facebook
  • Twitter
  • Reddit
  • Email
  • Tumblr

Like this:

Like Loading...

Category: How-to, The Basics Tags: CMB2, custom fields, post meta, Post Meta Bootcamp

← Post Meta.. How do I save it?
Post Meta.. Let’s make something! →

1 Comments on “Post Meta.. How do I save it? (add_post_meta)”

  1. Pingback: What is Post Meta? An intro to WordPress Custom Fields – DsgnWrks

CommentCancel reply

Recent Posts
  • It me!
  • “Is experience exactly the same as pessimism?”
  • WooCommerce: Allow adding multiple products to the cart via the add-to-cart query string
  • Interview on WP Elevation
  • End of an Era: Moving on from WebDevStudios
  • CMB to CMB2 – a migration tale
  • Don’t Repeat Yourself. Use WP Lib Loader instead!
  • What is the future of CMB2?

WordPress Plugin

WordPress Plugin

WordPress Plugin

WordPress Plugin
  • Feeling Generous? Feel free to buy me a coffee! :)
  • Home
  • Code
    • Plugins
      • BibleGateway Links Shortcode
      • CMB2
      • Code Snippets CPT
      • Cubify WP
      • DsgnWrks Importer for Instagram
      • Easy Digital Downloads – Internal Notes for Products
      • DsgnWrks Twitter Importer
      • Enhanced Admin Bar with Codex Search – WordPress Plugin
      • Google Analytics Top Content Widget – WordPress Plugin
      • Hash Link Scroll Offset
      • HTML5 Slideshow Presentation – WordPress Plugin
      • IFTTT Post Formats
      • Jetpack Slideshow Caption
      • Network Sites Counts Dashboard Widget
      • story|ftw
    • All projects
  • Talks
  • Connect
  • About
Twitter
My Tweets
Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Comments
  • Add Multiple Products to WooCommerce Cart using the fetch API - Insytful on WooCommerce: Allow adding multiple products to the cart via the add-to-cart query string
  • JT on DsgnWrks Importer for Instagram
  • andrewpschultz on DsgnWrks Importer for Instagram
  • Rory Heaney on DsgnWrks Importer for Instagram
  • TheBeersBeer on DsgnWrks Importer for Instagram

Copyright © 2025 · All Rights Reserved · DsgnWrks

Swell Theme from Organic Themes · RSS Feed · Log in

  • Github
  • Twitter
  • Linkedin
  • dribbble
%d