X

How to Attach Images with Simple Thumbnail Selection Metabox

Snippets by IsItWP

Are you looking for a way to attach images to posts with a simple thumbnail selection metabox? While there’s probably a plugin for this, we have created a quick code snippet that you can use to attach images to posts with a simple thumbnail selection metabox in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_action("admin_init", "images_init");
add_action('save_post', 'save_images_link');
function images_init(){
    	  $post_types = get_post_types();
    	  foreach ( $post_types as $post_type ) {
		add_meta_box("my-images", "Pictures", "images_link", $post_type, "normal", "low");
	  }
	}
function images_link(){
	global $post;
	$custom  = get_post_custom($post->ID);
	$link    = $custom["_link"][0];
	$count   = 0;
	echo '<div class="link_header">';
	$query_images_args = array(
		'post_type' => 'attachment',
		'post_mime_type' =>array(
                		'jpg|jpeg|jpe' => 'image/jpeg',
                		'gif' => 'image/gif',
				'png' => 'image/png',
				),
		'post_status' => 'inherit',
		'posts_per_page' => -1,
		);
	$query_images = new WP_Query( $query_images_args );
	$images = array();

	echo '<div class="frame">';

	$thelinks = explode(',', $link);

	foreach ( $query_images->posts as $file) {
	   if(in_array($images[]= $file->ID, $thelinks)){
	      echo '<label><input type="checkbox" group="images" value="'.$images[]= $file->ID.'" checked /><img src="'.$images[]= $file->guid.'" width="60" height="60" /></label>';
		 }else{
	      echo '<label><input type="checkbox" group="images" value="'.$images[]= $file->ID.'" /><img src="'.$images[]= $file->guid.'" width="60" height="60" /></label>';
		 }
		$count++;
	}
	echo '<br /><br /></div></div>';
	echo '<input type="hidden" name="link" class="field" value="'.$link.'" />';
	echo '<div class="images_count"><span>Files: <b>'.$count.'</b></span> <div class="count-selected"></div></div>';
}
function save_images_link(){
	global $post;
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){ return $post->ID; }
	update_post_meta($post->ID, "_link", $_POST["link"]);
}
add_action( 'admin_head-post.php', 'images_css' );
add_action( 'admin_head-post-new.php', 'images_css' );
function images_css() {
	echo '<style type="text/css">
        #my-images .inside{padding:0px !important;margin:0px !important;}
	.frame{
		width:100%;
		height:320px;
		overflow:auto;
                background:#e5e5e5;
		padding-bottom:10px;
		}
	.field{width:800px;}
	#results {
		width:100%;
		overflow:auto;
                background:#e5e5e5;
		padding:0px 0px 10px 0px;
		margin:0px 0px 0px 0px;
		}
	#results img{
		border:solid 5px #FDD153;
		-moz-border-radius:3px;
		margin:10px 0px 0px 10px;
		}
	.frame label{
		margin:10px 0px 0px 10px;
		padding:5px;
		background:#fff;
		-moz-border-radius:3px;
		border:solid 1px #B5B5B5;
		height:60px;
		display:block;
		float:left;
		overflow:hidden;
		}
	.frame label:hover{
		background:#74D3F2;
		}
	.frame label.checked{background:#FDD153 !important;}
	.frame label input{
		opacity:0.0;
		position:absolute;
		top:-20px;
		}
	.images_count{
		font-size:10px;
		color:#666;
		text-transform:uppercase;
		background:#f3f3f3;
		border-top:solid 1px #ccc;
		position:relative;
		}
	.selected_title{border-top:solid 1px #ccc;}
	.images_count span{
		color:#666;
		padding:10px 6px 6px 12px;
		display:block;
		}
	.count-selected{
		font-size:9px;
		font-weight:bold;
		text-transform:normal;
		position:absolute;
		top:10px;
		right:10px;
		}
		</style>';
}
add_action( 'admin_head-post.php', 'images_js' );
add_action( 'admin_head-post-new.php', 'images_js' );
function images_js(){?>
<script type="text/javascript">
jQuery(document).ready(function($){

  $('.frame input').change(function() {
	var values = new Array();
        $("#results").empty();

	var result = new Array();

	$.each($(".frame input:checked"), function() {
		result.push($(this).attr("value"));
		$(this).parent().addClass('checked');
	});
	$('.field').val(result.join(','));
	$('.count-selected').text('Selected: '+result.length);

	$.each($(".frame input:not(:checked)"), function() {
		$(this).parent().removeClass('checked');
	});

  });

	var result = new Array();
	$.each($(".frame input:checked"), function() {
		result.push($(this).attr("value"));
		$(this).parent().addClass('checked');
	});
	$('.field').val(result.join(','));
	$('.count-selected').text('Selected: '+result.length);

	$.each($(".frame input:not(:checked)"), function() {
		$(this).parent().removeClass('checked');
	});
});

</script>
<?}

function wps_thumbnails_list(){
	   global $post;
	   $image = get_post_meta($post->ID, '_link', true);
	   $image = explode(",", $image);
	   foreach($image as $images){
		$url = wp_get_attachment_image_src($images, 1, 1);
	        echo '<a href="';
		echo $url[0];
		echo '" class="lightbox">';
		echo wp_get_attachment_image($images,'thumbnail', 1, 1);
		echo '</a>';
		}
}

Add this snippet within the loop of your single.php file to display the images in your posts or pages.

<?
      wps_thumbnails_list()
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 11 best free web hosting services and how to migrate GoDaddy website builder site to WordPress.

Comments   Leave a Reply

  1. is there a reason for double jquery code?

  2. Great plugin. I have been trying to retrieve on the page or post the corresponding meta of each image without success. Did anyone figure it out or is it even possible with this plugin?

  3. I get white screen when including this code to functions.php. Im using WP 3.8, is there a fix? 🙂 Id like to use this.

  4. hello! What about Multiple Images Attached to One Thumbnail? Help me please

  5. Hi Kevin

    Just wandering instead of showing all the attachments in the Media Library, is there a way just to show uploaded images for each post they are attached to?

    Thanks

    1. Just add this

      ‘post_parent’ => $post->ID

      Under

      ‘posts_per_page’ => -1,

  6. Kevin, have you run into anything that allows image upload for user profile fields. I’ve seen a few premium plugins, and I’m guessing this has to be done with similar JS, but just wondering if you’ve come across any code for that.

    1. Do you mean like an avatar upload type thing ?

  7. Dante Francesco Passera July 6, 2012 at 11:51 am

    Thanks, man. Easy to use, as is, or a great starting point for customization.

    1. Cool glad to hear it, I’m currently working on a plugin version of this snippet that will support things like lazy load, popup image preview etc, and will be releasing it for free in the near future. Follow me on twitter or facebook ill be making an announcement about it.

  8. This is just super awesome. You mentioned in the comments of posting an updated version, just curious if you had done that already or not? Thanks for the cool snippet

  9. Seems like a great php function. Maybe its just my computer but it seems really laggy to me, anyway to speed it up?

  10. Nice start! But don’t use $file->guid. That will destroy the proportions. Use $thumbnail = wp_get_attachment_image_src($file->ID, ‘thumbnail’); and replace $file->guid with $thumbnail[0] instead. Much much better!

    1. Thanks Jens, ill have to post an updated version with the suggestions I have been getting. Glad to hear you like the snippet,

  11. Just wanted to say got it working finally, again, thank you. Your help is very much appreciated 🙂 

    1. No problem glad to hear you got things working properly.

  12. Hmmm, wasn’t aware that the  “AT kevin”  part would change to a twitter link with the username ‘kevin’
    Sorry about that 🙂 I was just replying at/to you Kevin (Chard).

    1. haha no problem 🙂

  13. @Kevin:twitter ,  wow this must be my lucky day, I’ve been looking for something like this for a while now! I am very gratefull, thank you! This is going to be handy and it works great, but I would like to know how to disable multi-select option, I only want the function to be able to select only one attachment 🙂

    (I already edited it to only show the url/source so I could implement it in the theme loop)…

    1. Just change this from checkbox to radio buttons all within the same group.

      1. Kevin, thank you but that did not work, first of all when selecting an image it selects the image but  if another image was already selected it does not de-select that one, and it still shows multiple images in the post  (not really a big problem, but more user friendly if a user can only select one image :))

        Secondly, I would like to know if its possible to show the size of the image in the alt or title section of , or beneath the image itself as in a span. Is this even possible wit this snippet? I tried the following:
        (I know it is not correct :))
        title=”””

        1. This should work for you, the radio buttons need to have the same name=”” otherwise they are not part of the same group and would function like a checkbox.

          http://pastebin.com/vF6mjyZL

          I made two version one that does single image for the same reasons you might have, both should work together although this has some commented out code but should work fine.

      2. What I’ve tried:
        title = “‘ ‘”

  14. Hi Sir, can I say that this is one of your best snippest? May !?

    1. Thanks glad to see that you like the snippet.

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!