Snippet: Media Metabox to add additional images to posts

This snippet adds a gallery metabox where admin can either upload images through WordPress Uploader or put in the image URL directly. This metabox is very useful for the custom post types for which you want to upload multiple images. Some good examples are, real estate properties, work portfolios and store products. All of these would have a featured image and some images to be displayed in a (for example) slider to explain it features and qualities.

You can specify number of images to upload, just change the constant on first line of snippet.

Media or Gallery Metabox

Media or Gallery Metabox

Snippet

/*
* Media/Gallery Metabox
* Author: WPDevSnippets.com
*/
define('WPDS_NUM_ADD_IMAGES',10); // Change number of images 
add_action('add_meta_boxes', 'wpds_media_meta_box');
add_action('save_post','wpds_save_media_mb');
function wpds_media_meta_box() {
    // change 'post' to any custom post type as per scenario
    add_meta_box('additional_images', 'Additional Images', 'additional_images_cb', 'post', 'normal');
}

function additional_images_cb($post) {
    
    echo '<table>';
    for($i=0; $i<WPDS_NUM_ADD_IMAGES; $i++){
        echo ($i%2==0) ? '<tr valign="top">':'';
        echo '<td valign=top width="40%"><input id="add_img'.$i.'_field" type="text" size="36" name="add_img'.$i.'" value="'.get_post_meta($post->ID,'add_img'.$i,true).'" />
        <input id="add_img'.$i.'" class="upload_buttons" type="button" value="Upload/Select" /></td><td width="10%">';
        if(has_additional_image($post->ID,$i) )
                echo '<a href="'.the_additional_image_url($post->ID,$i).' target="_blank"><img src="'.the_additional_image_url($post->ID,$i,array(30,30)).'" height=30 /></a>';
        echo '</td>';
        echo (($i+1)%2==0) ? '</tr>':'';
    }
    echo '
        <tr><td colspan="4">You can specify an image URL or an attachment ID through Upload/Select button</td></tr>
    </table>';
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function() {
            var formfieldID = '';
            var wpds_orig_send_to_editor = window.send_to_editor;
            jQuery('.upload_buttons').click(function() {
                formfieldID = jQuery(this).attr('id')+'_field';
                tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
                
                window.send_to_editor = function(html) {
                    attachmentID = html.match(/wp-image-([0-9]+)/);
                    if(attachmentID)
                        pasteValue = attachmentID[1];
                    else
                        pasteValue = jQuery(html).filter('img').attr('src');

                    jQuery('#'+formfieldID).val(pasteValue);
                    tb_remove();
                    window.send_to_editor = wpds_orig_send_to_editor;
                }
                return false;
            });

        });
    </script>
    <?
}

function wpds_save_media_mb($post_id) {

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return;

    if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id))
        return;

    for($i=0; $i<WPDS_NUM_ADD_IMAGES; $i++){
        if(isset($_POST['add_img'.$i]))
            update_post_meta($post_id, 'add_img'.$i, $_POST['add_img'.$i]);
    }
}

Check Existance of Image

Similar to “has_post_thumbnail“, Use the following following function to check the existance of an additional image.

function has_additional_image($post_id, $id=1) {
   
    $meta = get_post_meta($post_id,'add_img'.$id, true);
    if(empty($meta))    return false;
    return true;
}

Fetch Additional Image

Similar to “the_post_thumbnail“, use following function to get the additional image. Unlike “the_post_thumbnail“, this function returns the image URL without any HTML code.

function the_additional_image_url($post_id, $id=1, $size='post-thumbnail') {
    $meta = get_post_meta($post_id,'add_img'.$id, true);
    if(empty($meta))    return false;
    if(is_numeric($meta)){
        $image = wp_get_attachment_image_src($meta, $size);
        if(!empty($image))
            return $image[0];
        return false;
    }
    else{
        return $meta;
    }
}

12 Responses to Snippet: Media Metabox to add additional images to posts

  1. Jason says:

    Hi,is there any live demo how this meta image snippet works?

  2. JB says:

    I can’t get it to display in the post, what part should i place in the single.php?

    get_post_meta($post->ID,’wpds_media_meta_box’.$i,true)

    • Mohsin Rasool says:

      Instead of get_post_meta, use “the_additional_image_url(NULL,1)” to retrieve the URL of the first image. You should also check if user has selected any image using “has_additional_image” function with same parameters. You can find both of these function above.

      • JB says:

        unfortunately no success.

        I included all above funtions in functions.php , uploaded some images and placed

        the_additional_image_url($post_id, $id=1);

        in the post-template. Also tried by conditional tags with has_additional_images with same params, but unfortunately no succes.

        • Mohsin Rasool says:

          Please note that “the_additional_image_url” function returns the image URL not an HTML code. So you would use it like

          <img src="<?php echo the_additional_image_url($post_id, 1); ?>" alt="additional image" />

          If it still does not work, Check in database the values (or through get_post_meta function) of add_img1, add_img2…. It is also possible that you are fetching the wrong index of the image.

          • I have tried every possible scenario and I can not even get my template to pull the meta. I am simply trying to print the array to be used in a rotating banner for my new site.

  3. aamer says:

    hello author, I placed the code to functions.php. a meta box appeared on new post screen but it says there is an error on this line

    if(has_additional_image($post->ID,$i) )

    please help.

  4. Angelique says:

    Two quick questions:
    - Does the uploader use and sync with the default WP media uploader?
    - Is it possible to delete images through this interface?

    • Mohsin Rasool says:

      Yes, it uses the WordPress uploader and media files to manage images. Secondly, deleting is as easy as emptying the text box. If you want to delete the image, you can do it from WP medial library.

  5. Văn Đức says:

    Thank you ! Nice article .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>