X

Comment joindre des images avec la métabox de sélection de vignettes simple

Snippets by IsItWP

Vous cherchez un moyen d’attacher des images à vos articles avec une simple boîte de sélection des vignettes ? Bien qu’il existe probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour attacher des images aux articles avec une simple boîte de sélection de vignettes dans WordPress.

Instructions:

Tout ce que vous avez à faire est d’ajouter ce code au fichier functions.php de votre thème ou dans un plugin spécifique à votre site:

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>';
		}
}

Ajoutez ce code dans la boucle de votre fichier single.php pour afficher les images dans vos articles ou pages.

<?
      wps_thumbnails_list()
?>

Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez vous référer à notre guide sur la façon de copier/coller correctement des extraits de code dans WordPress, afin de ne pas casser accidentellement votre site.

Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 11 meilleurs services d’hébergement web gratuits et comment migrer un site GoDaddy vers WordPress.

Commentaires   laisser une réponse

  1. Markus Maurer août 7, 2014 à 4:19 pm

    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 juillet 6, 2012 à 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.

Ajouter un commentaire

Nous sommes heureux que vous ayez choisi de laisser un commentaire. N'oubliez pas que tous les commentaires sont modérés conformément à notre privacy policy, et que tous les liens sont en nofollow. N'utilisez PAS de mots-clés dans le champ du nom. Engageons une conversation personnelle et constructive.

WordPress Launch Checklist

L'ultime liste de contrôle pour le lancement de WordPress

Nous avons rassemblé tous les éléments essentiels de la liste de contrôle pour le lancement de votre prochain site Web WordPress dans un ebook pratique.
Oui, envoyez-moi le gratuit !