Reusable Custom Meta Boxes Part 4: Using the Data

Reusable Custom Meta Boxes Part 4: Using the Data

Tutorial Details
  • Program: WordPress
  • Difficulty: Moderate
  • Estimated Completion Time: 10-15 Minutes
This entry is part 4 of 4 in the series Reusable Custom Meta Boxes

In Part 1, Part 2 and Part 3 of our custom meta box template tutorial series, we learned how to make a reusable meta box that gets all of the field information from an easy to read, easy to duplicate array. A lot of the data is simple to use by just echoing the meta field in your template or through a function, but some of the fields are more complex and require a bit more finesse to use properly. This tutorial will give you a basic idea of how to use this data and can be expounded on in countless ways.


Getting the Data

WordPress provides multiple ways to get post meta data.

Output All of the Data at Once

The simplest way to display the data is with the_meta() function. You can drop this right into your single.php template, but it won’t give you the results you’re probably after. It is a very literal output of the data in an unordered list prefixed with the key of each field as shown in the picture.

the_meta

Get a Single Field

The most common way to get data saved in a post meta field is with the get_post_meta() function. This is a simple way to target a specific field and store it in a variable that can be used later.

$custom_text = get_post_meta($post->ID, 'custom_text', true);

Using this code within the single post loop would put the text "Some text in a basic text input" into the variable $custom_text which could then be echoed or filtered, or whatever you would want to do with the string. When you’re just dealing with a couple of fields, this is probably the way to go, but in our example, we are working with 11 different fields. Calling them all individually with this function would bloat your code unnecessarily since there’s a way to get all the data at once.

Get All of the Data at Once

My favorite method when I’m working with this many fields is to use the get_post_custom() function. With this function, we can store all of the custom post meta fields in one array and then retrieve the data we want with the array key.

$post_meta_data = get_post_custom($post->ID); will give us an array that looks like this:

Array
(
    [custom_text] => Array (
            [0] => Some text in a basic text input
        )
    [custom_textarea] => Array (
            [0] => A paragraph or two from a textarea. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique quam mi. Sed eget ligula sit amet ante dapibus tristique. 

Mauris vel enim mauris, vitae mattis tortor. Praesent at adipiscing massa. Fusce quis eros vel sem pharetra consequat imperdiet ut est.
        )
    [custom_checkbox] => Array (
            [0] => on
        )
    [custom_select] => Array (
            [0] => one
        )
    [custom_radio] => Array (
            [0] => two
        )
    [custom_checkbox_group] => Array (
            [0] => a:2:{i:0;s:3:"one";i:1;s:5:"three";}
        )
    [custom_post_id] => Array (
            [0] => 109
        )
    [custom_date] => Array (
            [0] => 05/25/2012
        )
    [custom_slider] => Array (
            [0] => 15
        )
    [custom_image] => Array (
            [0] => 413
        )
    [custom_repeatable] => Array (
            [0] => a:3:{i:0;s:22:"text from a repeatable";i:1;s:27:"more text from a repeatable";i:2;s:33:"repeatable text fields are great!";}
        )
)

As you can see from this array, WordPress stores each field as an array because it is possible to have more than one value for the same field. You’ll probably also notice that a few of the fields are serialized. Let’s dig more into handling the data from each field and cover how to fix that.


Simple Input Fields

The text and textarea fields are pretty simple to deal with. You can echo them with one of the following examples:

echo $post_meta_data['custom_text'][0];

echo apply_filters('the_content', $post_meta_data['custom_textarea'][0]);

$custom_checkox = $post_meta_data['custom_checkbox'][0];

if ($custom_checkbox == 'on') {
	do_stuff();
}

The first line will simply output the string as-is, and the second line will convert the line breaks to paragraphs with WordPress’ the_content filter. You can use these same methods for select, radio, date, and slider fields as well.

The last line shows how you can test to see if a checkbox has been selected or not. If it is, you can perform various functions, or any number of things.


Serialized Data

Our check box group fields and repeatable fields are storing arrays which get serialized in the database. Before we can output this data, we have to unserialize it.

$custom_checkbox_group = unserialize($post_meta_data['custom_checkbox_group'][0]);

$custom_repeatable = unserialize($post_meta_data['custom_repeatable'][0]);

The unserialize() function is a basic PHP function that converts our data into an array that is easier to use. The code above will give me two arrays that look like this:

Array
(
    [0] => one
    [1] => three
)
Array
(
    [0] => text from a repeatable
    [1] => more text from a repeatable
    [2] => repeatable text fields are great!
)

Now I can loop through the arrays however I want to use them in my output. It’s important to note that in the repeatable field, if you also make it sortable as our example in Part 3 of our custom meta box template tutorial does, the keys in the array will automatically store in the order of 0, 1, 2, 3, etc. and not in the order in which they were originally entered before sorting them.

echo '<ul class="custom_repeatable">';
foreach ($custom_repeatable as $string) {
	echo '&ltli>'.$string.'</li>';
}
echo '</ul>';

This example will output an unordered list of each string saved in the $custom_repeatable array.


Specialized Data

For our Post List and Image fields, we saved an ID. There may be some very rare cases in which you want to output just the ID, but most likely you’ll want to use the ID to get more information.

$custom_post_id = $post_meta_data['custom_post_id'][0];
echo '<a href="'.get_permalink($custom_post_id).'">'.get_the_title($custom_post_id).'</a>';

$custom_image = $post_meta_data['custom_image'][0];
echo wp_get_attachment_image($custom_image, 'thumbnail');

Conclusion

This tutorial shows the most basic ways that you can use the data that we’ve stored with our reusable custom meta boxes. Being able to save extra data and use it in themes and plugins opens up a whole new world of possibilities with WordPress. What will you use it for?


Other parts in this series:Reusable Custom Meta Boxes Part 3: Extra Fields
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.wpfix.org Wpfix

    Nice Tutorial.

  • Tim

    Tammy,

    Very nice and easy to follow tutorial. Better than others that I’ve seen on this same topic.

    How would you recommend to convert this for creating multiple meta boxes?

    Thanks,

    Tim

  • sebastien

    and now, after repeatable Fields : the repeatable metabox
    :-)
    is it possible ?

  • sebastien

    and… how create a textarea with visual editor…
    and a repeatable textarea with visual editor…
    :-))

    • http://www.tammyhartdesigns.com Tammy Hart
      Author

      Playing with the visual editor is tricky and dangerous. It’s not working very well in the moveable meta boxes yet. The simple answer is, instead of outputting a field, you would use wp_editor(): http://codex.wordpress.org/Function_Reference/wp_editor

  • http://www.derekshirk.com derek

    Great Tutorial.

    I was particularly interested in the repeatable fields portion. So far everything is working for me except except after sorting the entries on the edit post screen and saving the sorted entries revert back to their original order.

    I am hoping that once sorted and saved, I can have their order updated on the frontend of my site as well.

    I haven’t pinpointed the problem yet. What should I be focusing on in order to trouble shoot this?

    • http://www.derekshirk.com derek

      I think my problem has something to do with saving the repeatable fields because if I edit an existing “repeating” “sortable” field and hit save it reverts back to the original data.

      /*———————————————————————————–*/
      /* Save data when post is edited
      /*———————————————————————————–*/

      function tz_save_data($post_id) {
      global $meta_deployments;

      // verify nonce
      if (!wp_verify_nonce($_POST['tz_meta_box_nonce'], basename(__FILE__))) {
      return $post_id;
      }

      // check autosave
      if (defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE) {
      return $post_id;
      }

      // check permissions
      if (‘page’ == $_POST['post_type']) {
      if (!current_user_can(‘edit_page’, $post_id)) {
      return $post_id;
      }
      } elseif (!current_user_can(‘edit_post’, $post_id)) {
      return $post_id;
      }

      // loop through fields and save the data
      foreach ($meta_deployments as $field) {
      $old = get_post_meta($post_id, $field['id'], true);
      $new = $_POST[$field['id']];

      if ($new && $new != $old) {
      update_post_meta($post_id, $field['id'] );
      } elseif (” == $new && $old) {
      delete_post_meta($post_id, $field['id'], $old);
      }
      } // end foreach

      }

      add_action(‘save_post’, ‘tz_save_data’);

  • http://www.pushplaybang.com Paul

    Thanks for the great tutorial series so far, it was a long wait for this post, but its been an incredibly helpful series.

  • angel

    since image fields are exactly the same as text inputs can you explain how to add a repeatable image field?
    I kep getting a foreach error everytime I try and change it.

    also is there a way to create multiple meta bpxes with this?

  • derek

    Has anyone else been able to save the repeatable (sortable) fields after sorting them?

  • Danel

    Why are you leaving out the important part?
    When array entries contain quotes and special characters, you are not showing how the serialization would go in that case !?

    Say you one of the array antries looks EXACTLY like this : NUMO(12jp98å)M¨qwe2+3kr)=JE”3rnm5¨cm\”14v 3245cäaä iM˚~HE(392¨~’/32R RC2 RVAC ’ EM23 5V2O35K204Z,#J9MRJ=#M JJM(H#()”!^” €!C

    I know its a messy string, i actually encountered that exact one in my WP which broke everything. It was as a entity in $_POST['meta_field'][0] where entire $_POST['meta_field'] was serialized but to unserialize it, entire WP banged out :S

  • Jay

    Anyway you could also explain adding “insert Link” box to a meta box? sought of like prompt the insert link box to get a link to an internal page in WP as the value for a custom meta box?

  • http://about-lingerie.com Delcourt

    Hi Tammy

    the best tutorial I have found and I have read many…
    Thank you. It saved me a lot time.

    Regards,
    Dominique

  • Pingback: http://wp.tutsplus.com/tutorials/reusable-custom-meta-boxes-part-4-using-the-data/ | test

  • http://www.pragmatic-web.co.uk David Lockie

    Hi,

    Sorry to ask a ‘how-to’ via comments.

    Say I’ve created a custom meta field which is a checkbox group, containing a list of checkboxes (each with their own ID), what’s the syntax to add post meta to that?

    E.g. add_post_meta( $post_id, $checkbox_group_id=>$checkbox_id, $value );

    Does that make sense? What am I doing wrong? Thanks :)

    David

  • http://- Danyo

    Excellent Tutorial!

    I am trying to add the datepicker JS to the repeatable fields. I can get it to show on click, but when i add an extra field and click on it, the datepicker will only change the first field, and not the one currently selected.

    Any ideas on how i can fix this?

    Thanks, Danyo

  • Greed

    And how can I use the function WP_Query( $args ) with this???

  • DustyKhan

    How do i get this to work on a Page rather than a post i have the meta box displaying correctly when adding a new page, but I cant get it displaying the information (image is most important) on the page when using the information on this page!

    Please help

    Cheers DK

  • Robert

    Hello

    Great tutorial, but i have a question though

    The repeatable field is working fine but i can’z figure out how to disable the remove function if there is only one field. I know this should be easy to but the code breaks every time i try to change something so please help

    Thank you

    • Francis

      in custom-js.js

      replace this:

      jQuery(‘.repeatable-remove’).click(function(){
      jQuery(this).parent().remove();
      return false;
      });

      by this:

      jQuery(‘.repeatable-remove’).click(function(){
      var numInput = jQuery(“:input[id^=custom_repeatable]“).length;
      if (numInput !==1){
      jQuery(this).parent().remove();
      return false;
      }
      });

  • http://www.modelcitizen.com.au Kriss

    Fantastic work!

    Really good fucntionality – well explained.

    I’m using this in conjunction with custom post types and it really opens up the possibilites in wordpress!

    THANKS!

  • Francis

    by the way, nice tutorial!

    i have a question. How can I upload more than one image to create a gallery with the ‘choose image’ button?!

    thanks

  • http://www.patrickheiloo.nl Patrick Heiloo

    Hello,

    First: very nice tutorial, thanks!
    My question: Is it possible to add multiple fields within a repeatable field?
    I’m working on a events post type and I would like to use the repeatable fields for creating line-ups.

    This is the idea:

    [repeatable]
    - Text field: Name of the artist
    - Text field: Artist website
    - Checkbox: Headliner (Yes or no)
    [/repeatable]

    Hope you guys can help me out!

    Thanks :-)

  • jcnv

    Say I added a meta box to “Custom Post Type A” that associates “Custom Post Type A” with posts from “Custom Post Type B.” How can I output evidence of that association to single pages for “Custom Post Type B,” bidirectionally speaking?

    Am I required to build a second association for “Custom Post Type B” that essentially requires the user to do double work?

    This idea seems entirely possible here, maybe with query_var, but I can’t quite place it!

  • Jason

    Is it possible to sort posts by the value of a particular metabox?

    For example, I have a text type meta-box and I want to sort posts using WP_query() by that value of that meta box.

    Thanks in advance

  • Mihai

    Hi,

    I can’t get the values to show.

    I have the following code:

    ID, ‘custom_text’, true); echo $custom_text ?>

    The custom meta box is on a static homepage.

    When I look at the source code, the h2 is empty.

    Thanks!

    • http://twitter.com/mvanboordt Michel van Boordt

      Any luck with this? I have the same problem

  • vaibhav Patil

    How to add different metabox group for specific page layout only.

  • http://www.facebook.com/patrickheiloo Patrick Heiloo

    Hi,

    I’m using the Reusable Custom WordPress Meta Boxes from your GitHub page.
    Currently I’m working on a portfolio post type and I would like to use the repeatable fields for uploading images for creating a gallery.
    So every field has it’s own upload button with a preview thumbnail after uploading.

    This is the idea:

    [repeatable]
    - ||| Handler
    - [preview image after successful upload]
    - “Select image” button
    - “Remove image” button (removes the repeatable field)
    [/repeatable]

    How do I create this? Hopefully you guys can help me :-)

  • ratsoid

    Is there a way to have multiple fields inside the Repeatable metabox? I have problems with sorting. Thanks!

  • http://twitter.com/donbwhite Donald White

    Any idea on how to have the output for the datepicker only show the month and year? i.e. MM/YYYY?

  • http://www.facebook.com/mikevisions Mike Dutton

    Thanks for the interesting tutorial.
    I would be interested to learn how to order the post/page list alphabetically, thanks.

  • http://www.facebook.com/kerry.geiger Kerry Geiger

    Great — saved me much time and gave me great insight into using metaboxes more effectively

    I added a PDF Upload if anyone is interested

    array(
    ‘label’ => ‘PDF Upload’,
    ‘desc’ => ‘If you have a PDF version of the article or release, upload it here.’,
    ‘id’ => $prefix.’pdfupload’,
    ‘type’ => ‘pdfupload’
    )

    —————————–

    // pdfupload
    case ‘pdfupload’:
    if ($meta) { $pdfuri = wp_get_attachment_url($meta); }
    echo ‘

     Remove PDF File
    ‘.$field['desc'].”;
    echo ‘Current file: ‘.$meta.”;
    break;

    ——————————-

    jQuery(‘.custom_upload_pdfupload_button’).click(function() {
    formfield = jQuery(this).siblings(‘.custom_upload_pdfupload’);
    preview = jQuery(this).siblings(‘.custom_default_pdfupload’);
    tb_show(”, ‘media-upload.php?TB_iframe=true’);
    window.send_to_editor = function(html) {
    pdfurl = jQuery(html).attr(‘href’);

    //classes = jQuery(‘img’, html).attr(‘class’);
    //id = classes.replace(/(.*?)wp-image-/, ”);
    formfield.val(pdfurl);
    //preview.attr(‘src’, imgurl);
    preview.text(“Current file: “+pdfurl);
    tb_remove();
    }
    return false;
    });

    jQuery(‘.custom_clear_pdfupload_button’).click(function() {
    var defaultImage = jQuery(this).parent().siblings(‘.custom_default_pdfupload’).text();
    jQuery(this).parent().siblings(‘.custom_upload_pdfupload’).val(”);
    jQuery(this).parent().siblings(‘.custom_default_pdfupload’).text(“No PDF Uploaded”);
    return false;
    });