wordpress snippets last updated   : September 29, 2014
we now have 639 snippets

Attach images with simple thumbnail selection metabox

wordpress snippet

A little snippet I wrote recently to easily attach images to posts with a simple thumbnail selection metabox. Add the first snippet to the functions.php of your wordress theme. Place the second snippet within the loop of your wordpress theme to display the images in your posts or pages.

This snippet will do the job although it could use some tweaking that ill delve into in the future with an update. I found this much easier for clients to select images without going into the library and attaching images to posts. ( example screenshot )
snippet :  PHPcopy
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>';
		}
}
snippet :  PHPcopy
<?
      wps_thumbnails_list()
?>

Did you like this post? If so please share it with your friends. Thanks!

  • Fred

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

    • http://wpsnipp.com Kevin Chard

      Thanks glad to see that you like the snippet.

  • ENIX

    @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)…

    • http://wpsnipp.com Kevin Chard

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

      • ENIX

        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=”””

        • http://wpsnipp.com Kevin Chard

          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.

      • ENIX

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

  • ENIX

    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).

    • http://wpsnipp.com Kevin Chard

      haha no problem :)

  • ENIX

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

    • http://wpsnipp.com Kevin Chard

      No problem glad to hear you got things working properly.

  • Jens Törnell

    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!

    • http://wpsnipp.com Kevin Chard

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

  • http://www.leachcreative.com/ Andrew Leach

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

  • http://www.codedevelopr.com/ Jason Davis

    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

  • http://www.facebook.com/b0ne.rzD00d Dante Francesco Passera

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

    • http://wpsnipp.com Kevin Chard

      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.

  • Craig

    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.

    • http://wpsnipp.com Kevin Chard

      Do you mean like an avatar upload type thing ?

  • Karl Barton

    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

    • samito

      Just add this

      ‘post_parent’ => $post->ID

      Under

      ‘posts_per_page’ => -1,

  • ikh

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

  • http://richardmisencik.com/ Richard

    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.

  • Facinet Touré

    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?

  • Markus Maurer

    is there a reason for double jquery code?