Blog

Sharing WordPress tips and tricks as I find them

Custom Metaboxes 0.7

This post has been marked as old. The code might no longer work. Comments have been disabled as this is no longer maintained. Use the search on the right to find a newer tutorial.

» Download the CMB Library here

It’s been about six months since my original Custom Metaboxes post announcing the release of this code library for easily creating metaboxes. If you haven’t had a look at it since then, I highly recommend you hop on Github and look at the latest version and the wiki.

Some of the features:

My favorite field types:

  • WYSIWYG. If you’re using WordPress 3.3, this will automatically use the new wp_editor which gives you a ton of flexibility.
  • Taxonomy field types (select, radio, multicheck). If you’re dealing with a lot of taxonomies, the default metabox provided by WordPress takes up a lot of screen real estate. Include taxonomies in your custom metabox instead. Using select or radio is also a great way to force users to only select one taxonomy term.
  • File upload. Use the built-in media uploader to allow the user to upload any file they want. You can also store the attachment ID in case you want to retrieve other image sizes.
  • Title. If your metabox has a lot of fields in it, use the title field type to create subheadings and instructions.
  • Text (standard, medium, and small). This is as simple as it comes, but also the one you’ll use most often.
  • text_date_timestamp. This one uses a date picker to let the user select a date, and then saves it as a UNIX timestamp. This is great for event metaboxes because you can then query based on the date.

The contributors of this code library, in no particular order, include: Andrew Norcross, Jared Atchison, Travis Smith, Randy Hoyt, Jeremy Pry, Andrew Ryno, Patrick Forringer, Chris Olbekson, Stefan Crain  …and me.

Please use this code, and consider contributing any improvements you make. If you create any field types or show_on filters, post them on the wiki. If you find any bugs, post them in issues (and even better, post the fix!).

72 Comments

  1. Looks brilliant Bill, cracking job from all involved.

    With such a comprehensive set of options, perhaps it’ll be included in a future of release of WordPress as default?

    However, i just did a quick basic install on a 3.3 and got an error…

    Parse error: syntax error, unexpected $end in /home/public_html/wpTest/wp-content/themes/testing/meta-boxes/meta-box-text/example-functions.php on line 179

    Something i’ve done?

  2. Cool, thanks for the update, I’m going to try out the WYSIWYG on a client site who needs a 2 column page layout!

    • Bill Erickson says:

      There’s two other things you might try depending on your clients needs. If every page will have two columns, you might pre-populate the main editor with two divs, then update the editor stylesheet to visually float them. That way the client can actually see two columns in the editor and put content in them (tutorial).

      If you want more flexibility with your layouts and using Genesis, I like to use the genesis column classes along with the Display Posts Shortcode. So I’ll put this in the editor to make two columns:

      [div class="one-half first"] This is the left column [end-div] [div class="one-half"] Right column [end-div]

      • Can you use that smashing mag tut for adding pre-populated divs to the meta-box WYSIWYG editor, or can you only connect to the main one i wonder?

        • Bill Erickson says:

          To be honest I have no idea. I’ve never tried the code in that tutorial, I just have it bookmarked to try in the future. Try it out and post the results!

      • thanks for the suggestions Bill. I did actually try the smashing mag method, but was running into some issues… I’ll have to give it another try. The client is really not web savvy, so I need to make it really easy for them

  3. so I added a WYSIWYG to a CPT , but when I try inserting a gallery into the main post WYSIWYG area, it keeps inserting it in the metabox.
    can you help?
    thanks

    • Bill Erickson says:

      You’ll need to upgrade to WordPress 3.3. This is one of the many issues with the previous wysiwyg, and if you’re running 3.3 it automatically uses the new wp_editor function which fixes them all.

  4. Great job and definitely time-saver as well! GPL I would imagine?

    Cheers,
    Emil

  5. Hey, this is really great. Just one question…
    How do we display chosen options in checkboxes, or radio buttons, on the front end? I searched the wiki and available documentation, but couldn’t find any….

    in my single.php template, Ive managed to display information on the front end, using this regular call:
    ID, “_cmb_test_textarea”, true); ?>
    But this is just simple text area information.

    Figuring out how to show Radio button selections, or Check box selection on the front end is whats left. Any directions for where i could find it?

    Thanks a bunch.

    • Bill Erickson says:

      It’s stored as postmeta like all the other ones. If you have a radio button or checkbox with an id of ‘be_sample’, you could retrieve its value like this: $value = get_post_meta( $post->ID, 'be_sample', true );

      • Hi Bill,
        I did try a variation…
        ID, '_cmb_test_multicheckbox', true);

        foreach($value as $value) {
        echo ''.$value.'';
        }

        ?>
        …and a few others, but i seem to be doing something wrong…

        • Bill Erickson says:

          I’m not sure if the code is getting cut off when you post, but this is the second time your code example has been missing this at the beginning: $value = get_post_meta( $post->.

          There’s no need for the foreach, just echo $value;

          If you run the_meta(); in the loop you’ll be able to see all the post’s metadata to ensure you’re using the right field names

          • True, the code gets cut off after I click submit… even when i tried using ‘code’ in arrow-brackets before/after. I’ll use Pastebin.
            I’m using your sample cmb code in a test setup.
            It works well in wp-admin for entering data, but the content-single.php display on the website is not coming through for:
            1. multicheck boxes.
            2. its different for radio buttons.
            havent tried to display the other field types yet in single.php

            For clarity, I’ve pasted the code I’m using in pastebin: http://pastebin.com/zFhHcgay

            It would be great to have the correct method for front-end display for each field type on the wiki – after all, the example-functions.php to set up field types is there, it would round it off to have the single.php display code too…

            Thanks a bunch for your interest.

          • Bill Erickson says:

            Multicheck boxes are stored as an array. Use false as the third parameter of get_post_meta.

            In testing this, I found an issue with multicheck boxes. Every time you save the post, the meta is saved again. You end up with an array with lots of values. Until this is fixed (should be soon), use this to get just the unique values: $multicheck = array_unique( $multicheck );

  6. Should the WYSIWYG print the content out the front end the exact same way has the default main top WYSIWYG?

    As using the current release straight out of the box just prints it as a text block with no p tags etc?

    I had enable wpautop for it to even register the p tag…

    Might be worth keeping an eye on :)

    • Bill Erickson says:

      Yes, you need to wrap it in wpautop if you want paragraphs. If you want all the filters that are applied to the content, use: echo apply_filters( 'the_content', $meta ); (assuming you’ve loaded the content into $meta).

      The main wysiwyg doesn’t actually apply paragraphs, it has wpautop attached to the ‘the_content’ filter. This filter also has do_shortcodes, oembed support…

  7. Nice job Bill.

    I’m using the library at the moment to create a second editor for right hand column text on a site that I’m working on. I’m using WordPress 3.3.

    Code works fine, metabox and editor is created with no problems. However I have an issue when trying to insert an image into a post. I’m left with a blank white overlay window and the image is not inserted into the post.

    If I take the code out of functions.php image inserting works again. There are no apparent PHP errors.

    Any tips would be great.

    Thanks

  8. Nice job!
    This has helped me tremendously and has saved so much time. I love how easy it is to use the meta boxes in an individual page templates. So easy and understandable!

    My only question is about showing the meta info in the front end for the regular metaboxes. Is there any documentation that shows this? I’ve been trying to display it by using this:

    ID, ‘test_metabox’, true ); ?>
    and then trying to echo it:

    Thanks for all of your help! The plugin is really great!

  9. Jon Breitenbucher says:

    Bill,

    I’m running into an issue trying to display taxonomy_multicheck. I know this is stored as an array. When I include the_meta() I see

    (code removed, use gist)

    Building, Seating, etc are the multicheck fields. What I can’t figure out is why the stored value is not the text of the taxonomy entry and is the numeric value. “48″ in building should be “Kauke” and “70″ in capacity should be “40 to 50″. If I try to use

    (code removed, use gist)

    the returned value is Array and doing $project_text[0] will return 70 and not 40 to 50. Either I’m missing something (limited PHP experience, so possible) or the values are not being stored correctly. Thanks.

    • Bill Erickson says:

      Yes, it stores those as an array of IDs. As described here, it’s better for data integrity to use IDs than their labels. Use get_term_by( 'id', $project_text[0], 'seating_capacity' ); to get all the labels and other information related to that term.

  10. Jon Breitenbucher says:

    Thanks. I think there is an even easier method which I point out at https://gist.github.com/1547439

  11. Hey Bill,

    how do I display the URL of a file upload?
    this gives me the attachment page URL:
    get_post_meta( get_the_id(), ‘_cmb_wpc_doc_attachment’, true )
    but I want the direct link to the file

    thanks

    • I figured it out, it’s because of XAMPP. works fine on a live server.

      but another question: how to display the ‘name’ part of the select dropdown? I don’t think it’s saved in the database?

      • Bill Erickson says:

        No it isn’t. That is just there so that you can present a different label to the user on the backend than the actual value you’re saving:

        array( 'name' => 'Another Value', 'value' => 'another-value' )

  12. Bill,

    Have you noticed any issues with multiple custom post types? I tried having three different custom post types at one point and for some reason the meta boxes only showed up on two of them, even those they were all called out correctly and worked if I turned one of them off. Any thoughts?

    Cheers,
    Joshua

  13. Bill,

    I can’t seem to display an uploaded image/file in the loop. I can get any other meta to display, but not the image file. I have ‘type’ set as ‘file’. I tried this: ID,’enrich_image’,true); ?> but no luck. I’m assuming it would just echo the url to the file, correct? It doesn’t display anything.

    Thanks,
    Joshua

  14. sorry, code: ID,’enrich_image’,true); ?>

  15. Yet again, ignore my comments, sorry!

  16. I’m trying to add a file upload to the metabox for a custom post type. The code for the metabox can be seen at https://gist.github.com/2948888 Everything is working fine except for the Business logo upload. When I am editing a post using this custom metabox and click on Upload, nothing happens. This is on my local MAMP setup. I haven’t tried it on a staging server. Any thoughts?

  17. I’m using the file upload field allowing users to upload a file, image, or URL. The upload works fine but what I am having trouble with is displaying what is uploaded. Obviously if the user uploads a file or URL then I need to display the link to the file or display the URL as a working URL. If they upload an image then I need to display the image. I’m just not sure what the best way to approach this is. Any ideas?

    • Bill Erickson says:

      A URL to whatever file they upload is stored in the post meta field you provide. So if you’re using the example code to generate your file upload field, you would retrieve it on the frontend using get_post_meta( $post->ID, '_cmb_test_image', true );

      • Thanks Bill. So I need to do some conditional check to see if it is an image, URL, or file if I want to display the image and display links in the other cases?

        • Bill Erickson says:

          Correct. What I’d do is, on the file upload field, add ‘save_id’ => true, which will save an additional field named “your_key”_id that contains the attachment id.

          Then use get_post_mime_type() to determine what kind of file it is, and use that information to determine how it is displayed.

  18. Wow,
    thank you man for this lib. Really very usefull and clever piece of code.
    But (there is always on of those … ;) ), it seems that the issue with CMB_META_BOX_URL and my Win machine is in business here …
    I’m not gettin’ any js and css … (no datepicker etc.).
    You mentioned that this error is fixed, and I cannot find anything on Wiki … :(

    • Bill Erickson says:

      Here’s the issue with a possible fix included: https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress/issues/31

      Try it out and comment! We need people to test this fix before we can add it to core.

      • Hey, thnx for fast reply.
        Yeah, since I’m not really a programmer, a lot of that stuff there I just don’t understand (yet).
        So, I solved it (for my needs) with simple:
        define( ‘CMB_META_BOX_URL’, get_template_directory_uri() . ‘/custom_meta/’ );
        Could this work ? Nor only on my local machine, I mean …?

        In any case, BIG thanks. :)

        • Bill Erickson says:

          Yes, that will work as long as you place the code in your theme but not if you put it in a plugin. The reason we don’t use that is this code can be used either in a theme or plugin (I always use it in /mu-plugins)

          • I will use this in my theme (and use it well ;) ), not plugin. but in case I’ll decide to make a plugin out of it …. I won’t, because, you’ll make it… LOL … just kidding
            Very nice work, and thanks for sharing it … :)

  19. Thanks for this plugin, really well done and well written.

  20. Awesome. FInished digging the Wikis for the plugin and everything looks great.
    One question though, can you show an example on how to outpuf the metabox data on specific post/page/cpt?

    The one here is specifically to show the metabox while writing a post:
    https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress/wiki/Display-Options

    Can you share some example code to show the data from the metaboxes to post/page or cpt?

  21. Hi Bill.
    I would like to ask few question about this plugin.

    1. If I use the wsyig type metabox, when I put a video url from url, will it autoembed?
    2. If I want to use the taxonomy radio or taxonomy select type, will the output linked to the taxonomy archive?

    • Bill Erickson says:

      1. There are no filters applied to the meta fields. But, if you wrap your output in ‘the_content’ filter it will receive all the same filters as the post content (add paragraphs, do shortcodes, autoembed…). Example.

      2. The taxonomy fields should ONLY be used for replacing the backend metabox for selecting taxonomy terms. When you register the taxonomy, specify show_ui => false. You can then create your own metabox for managing the taxonomy (radio, select…). Don’t use get_post_meta() to access this data. The metaboxes will store something (I think the taxonomy term slug), but the important thing is it updates the actual taxonomy terms on the post. So use get_the_terms() to retrieve the taxonomy terms attached to the current post, and display them however you want.

  22. This is great.

    One question, though: Is there something I can do to stop the auto-insert of a value into the text_date_timestamp fields? I’m working on a site for a local indie theatre, and they usually show movies 3 times a weekend, so I’ve set up 3 ‘showtime’ fields using text_date_timestamp CMBs. But sometimes a show will happen only twice or even once (say a midnight movie). If I leave the text_date_timestamp fields blank and publish or update the post, they get filled in with the current date and time. I’d like them to be empty. Is there a jQuery or WP function I can call to ensure this happens?

    (I did find a workaround — if I enter zeroes into both fields, it’ll be left blank. But I don’t want to have to remember that little kludge every time I fix a typo or something.)

    Thanks!

  23. I want to replace the standard Wysiwyg editor for the post content with a smaller textarea. I’ve removed the editor using ‘supports’ => false in my Custom Post Type definition.
    But which ID value do I need to use for the metabox? I’ve tried ‘post_content’ and a couple of other terms, but the text is not saved. (When I use ‘post_title’, the text is saved to the title field, so that does work.)

  24. Hey, I’m posting this again as I’m not sure it got through! I’m using the custom meta boxes to control how many images a user can attach to their post, which is working pretty well. The only problem is that when I retrieve the image I was to be able to dictate which size to use from my custom image sizes, but I can’t seem to pass this to the link. Is there a way to do this?
    echo “ID, ‘image1′,300, true).”>”;
    Thanks

    • Bill Erickson says:

      When you loop through the attached images, use wp_get_attachment_image_src( $image_id, $size ) to get the image at the size you want.

  25. Thanks for your previous reply – it pointed me in the right direction and eventually I was able to retrieve the image at the size I want.
    Another question: I’d like to simplify the media uploader to get rid of the fields such as the size pickers, the alt, title and description boxes as users of my site are finding that confusing. I’ve done some digging but not found anything as yet – is there a way to customise the meta plugins to do this?
    Thanks!

  26. I’m using a CMB on a project and I can’t seem to retrieve posts based on custom meta from my custom post type via url. An example would be trying to retrieve all active wholesale properties.

    Here is my meta

    wpb_dealtypeselect

    and the value that I’m trying to retrieve is Active Wholesale.

    Now, when I create taxos and custom meta manually, the value would be active-wholesale, so I’m assuming the same is in this case…but I’m not getting anywhere for whatever reason. I know I’m missing something.

    I’ve tried domain.com/wpb_dealtypeselect/active-wholesale/ but that doesn’t seem to be doing the trick

    If you could point me in the right direction that would be awesome.

    • Bill Erickson says:

      WordPress does not provide url-based meta queries. You’ll either need to rebuild it using a taxonomy which does allow url-based queries, or create a rewrite endpoint and customize the WordPress query to use that for your meta queries.

      More Information:
      http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint
      http://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/

      • yeah…thanks Bill…I remembered that after I went to bed. I’ve been working on too many things over the weekend with little sleep and after my comment last night, I threw my hands up in the air and said “ah whatever, I’m going to bed”

        no sooner than I went to bed, I remembered that custom_meta isn’t queriable within url parameters and decided that I’m going to have to convert it over to a custom taxo.

        HOWEVER….I’m one of those ambitious guys that always says “you can do anything with code”, so when I got up this morning, I was like “blzzzt, there has to be a way, and I’m going to find it” Then I checked my email and saw your response….so thank you for keeping me from spending an hour or two in the codex trying to find a solution for something that doesn’t exist. this morning. lol

  27. Bill, how would you remove post metaboxes like “Layout Settings” and “Theme SEO Settings”. I don’t want my users writing posts and feeling confused if they should use any of those options. Ideally only non-admins should not see those posts boxes, but I should in case I want to choose the layouts etc.

    • Bill Erickson says:

      remove_post_type_support( ‘post’, ‘genesis-layouts’ );
      remove_post_type_support( ‘post’, ‘genesis-seo’ );

  28. I am using your metaboxes and thanks for this great tool.
    However, I have some issue on how to print on front end the values of the following functions http://pastebin.com/m5Qfm4pj
    I will appreciate any help. thanks