Você está procurando uma maneira de anexar imagens a publicações com uma simples metabox de seleção de miniaturas? Embora provavelmente exista um plug-in para isso, criamos um trecho de código rápido que você pode usar para anexar imagens a publicações com uma simples metabox de seleção de miniaturas no WordPress.
Instruções:
Tudo o que você precisa fazer é adicionar esse código ao arquivo functions.php do seu tema ou em um plug-in específico do 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>'; } }
Adicione esse snippet dentro do loop do seu arquivo single.php para exibir as imagens em suas postagens ou páginas.
<? wps_thumbnails_list() ?>
Observação: Se esta é a primeira vez que você adiciona trechos de código no WordPress, consulte nosso guia sobre como copiar/colar corretamente trechos de código no WordPress, para não danificar seu site acidentalmente.
Se você gostou desse snippet de código, considere dar uma olhada em nossos outros artigos no site, como: 11 melhores serviços gratuitos de hospedagem na web e como migrar o site do construtor de sites GoDaddy para o WordPress.
is there a reason for double jquery code?
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?
This will show you how to get metadata,
http://wpsnipp.com/index.php/loop/display-attachment-thumbnail-with-image-metadata/
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.
hello! What about Multiple Images Attached to One Thumbnail? Help me please
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
Just add this
‘post_parent’ => $post->ID
Under
‘posts_per_page’ => -1,
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.
Do you mean like an avatar upload type thing ?
Thanks, man. Easy to use, as is, or a great starting point for customization.
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.
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
Seems like a great php function. Maybe its just my computer but it seems really laggy to me, anyway to speed it up?
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!
Thanks Jens, ill have to post an updated version with the suggestions I have been getting. Glad to hear you like the snippet,
Just wanted to say got it working finally, again, thank you. Your help is very much appreciated 🙂
No problem glad to hear you got things working properly.
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).
haha no problem 🙂
@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)…
Just change this from checkbox to radio buttons all within the same group.
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=”””
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.
What I’ve tried:
title = “‘ ‘”
Hi Sir, can I say that this is one of your best snippest? May !?
Thanks glad to see that you like the snippet.