Télécharger la vignette de l'article depuis le front-end
1 réponses
- votes
-
- 2011-03-07
Letéléchargement defichiersen ajaxest unpeu délicat cariln'estpaspossible detélécharger desfichiers à l'aide de l'objet XMLHttpRequest dunavigateur,vous devez donc utiliser une sorte deplugin detéléchargement Ajaxet leplus simple serait le < cycleJQuery Form Plugin quifacilite les choseset estinclus dans WordPress. Donc,pour l'utiliser,vous devez lemettreen file d'attente:
add_action('wp_print_scripts','include_jquery_form_plugin'); function include_jquery_form_plugin(){ if (is_page('12')){ // only add this on the page that allows the upload wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'jquery-form',array('jquery'),false,true ); } }
sur cettepage,ajoutez votreformulaire detéléchargementet le JQuerypour appeler leplugin JQuery Formparexemple:
<form id="thumbnail_upload" method="post" action="#" enctype="multipart/form-data" > <input type="file" name="thumbnail" id="thumbnail"> <input type='hidden' value='<?php wp_create_nonce( 'upload_thumb' ); ?>' name='_nonce' /> <input type="hidden" name="post_id" id="post_id" value="POSTID"> <input type="hidden" name="action" id="action" value="my_upload_action"> <input id="submit-ajax" name="submit-ajax" type="submit" value="upload"> <form> <div id="output1"></div> <script> $(document).ready(function() { var options = { target: '#output1', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse, // post-submit callback url: ajaxurl // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php }; // bind form using 'ajaxForm' $('#thumbnail_upload').ajaxForm(options); }); function showRequest(formData, jqForm, options) { //do extra stuff before submit like disable the submit button $('#output1').html('Sending...'); $('#submit-ajax').attr("disabled", "disabled"); } function showResponse(responseText, statusText, xhr, $form) { //do extra stuff after submit } </script>
vous devezmettre àjour POSTID avec l'ID depublication réel. puis créez lafonction Ajaxpour accepter letéléchargement dufichieret mettre àjour la vignette de l'article
//hook the Ajax call //for logged-in users add_action('wp_ajax_my_upload_action', 'my_ajax_upload'); //for none logged-in users add_action('wp_ajax_nopriv_my_upload_action', 'my_ajax_upload'); function my_ajax_upload(){ //simple Security check check_ajax_referer('upload_thumb'); //get POST data $post_id = $_POST['post_id']; //require the needed files require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); //then loop over the files that were sent and store them using media_handle_upload(); if ($_FILES) { foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) { echo "upload error : " . $_FILES[$file]['error']; die(); } $attach_id = media_handle_upload( $file, $post_id ); } } //and if you want to set that image as Post then use: update_post_meta($post_id,'_thumbnail_id',$attach_id); echo "uploaded the new Thumbnail"; die(); }
j'espère que cela vous aidera
Uploading files in ajax is a bit tricky because it is not possible to upload files using the browser's XMLHttpRequest object so you need to use some kind of Ajax upload plugin and the easiest one would be the the JQuery Form Plugin which makes things much easier and it's included in WordPress. So to use it you need to enqueue it:
add_action('wp_print_scripts','include_jquery_form_plugin'); function include_jquery_form_plugin(){ if (is_page('12')){ // only add this on the page that allows the upload wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'jquery-form',array('jquery'),false,true ); } }
on that page add your upload form and the JQuery to call the JQuery Form plugin for example:
<form id="thumbnail_upload" method="post" action="#" enctype="multipart/form-data" > <input type="file" name="thumbnail" id="thumbnail"> <input type='hidden' value='<?php wp_create_nonce( 'upload_thumb' ); ?>' name='_nonce' /> <input type="hidden" name="post_id" id="post_id" value="POSTID"> <input type="hidden" name="action" id="action" value="my_upload_action"> <input id="submit-ajax" name="submit-ajax" type="submit" value="upload"> <form> <div id="output1"></div> <script> $(document).ready(function() { var options = { target: '#output1', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse, // post-submit callback url: ajaxurl // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php }; // bind form using 'ajaxForm' $('#thumbnail_upload').ajaxForm(options); }); function showRequest(formData, jqForm, options) { //do extra stuff before submit like disable the submit button $('#output1').html('Sending...'); $('#submit-ajax').attr("disabled", "disabled"); } function showResponse(responseText, statusText, xhr, $form) { //do extra stuff after submit } </script>
you must update POSTID with the actual post ID. then create the Ajax function to accept the file upload and update the post thumbnail
//hook the Ajax call //for logged-in users add_action('wp_ajax_my_upload_action', 'my_ajax_upload'); //for none logged-in users add_action('wp_ajax_nopriv_my_upload_action', 'my_ajax_upload'); function my_ajax_upload(){ //simple Security check check_ajax_referer('upload_thumb'); //get POST data $post_id = $_POST['post_id']; //require the needed files require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); //then loop over the files that were sent and store them using media_handle_upload(); if ($_FILES) { foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) { echo "upload error : " . $_FILES[$file]['error']; die(); } $attach_id = media_handle_upload( $file, $post_id ); } } //and if you want to set that image as Post then use: update_post_meta($post_id,'_thumbnail_id',$attach_id); echo "uploaded the new Thumbnail"; die(); }
hope this helps
-
C'estgénial.Juste quelques questions.Autrement dit,oùtout doit aller.Évidemment,leformulaire va sur lapageen questionet ce sera l'identifiant depublication avec lequel utiliser.Lapremière action d'ajoutest cellepour la zone HEAD oupour lefunctions.php.et le dernierbloc ajax commençantpar//hook l'appel ajax.Où cela va-t-il.Mercibeaucoup.This is brilliant. Just a couple of queries. That is, where does everything need to go. Obviously the form goes on the page in question and that will be the post id with which to use. The first add action is that for the HEAD area or for the functions.php . and the final ajax block starting with //hook the ajax call. Where does that bit go. Many thanks.
- 0
- 2011-03-09
- Robin I Knight
-
lepremieret le dernierextrait de codepeuvent êtreplacésn'importe où dans votrefunctions.phpet le deuxièmeextrait doit êtreplacé sur lapage sur laquelle vous souhaitez afficher votreformulaire detéléchargement,vouspouvez égalementtransformer le deuxièmeextraiten un shortcodepourfaciliter les choses.the first and last snippets of code can be placed anywhere in your functions.php and the second snippet needs to be place on the page you wish to display your upload form on, you cal also turn the second snippet to a shortcode to make things easier.
- 0
- 2011-03-09
- Bainternet
-
Ce queje ne comprendspas,c'est comment leformulaire sait-il utilisermy_ajax_upload ()?Celane devrait-ilpas êtreinclus dans l'appel ajax?Jepose cette questionparce quej'ai uneboucle d'articles quej'autorise à êtremodifiéset qu'ils ontbesoin de différentesfonctionspourtraiter certains articles.What I don't get about this is how does the form know to use my_ajax_upload()? Shouldn't that be included in the ajax call? I ask this because I have a loop of posts that I'm allowing to be edited and they need different functions for processing certain posts.
- 0
- 2012-11-29
- Pollux Khafra
-
Leformulaire sait utilisermy_ajax_upload car sa valeur d'actionest accrochée (`add_action (...`) à lafonction `my_ajax_upload`.The form knows to use my_ajax_upload because its action value is hooked (`add_action(...`) to `my_ajax_upload` function.
- 0
- 2012-11-29
- Bainternet
-
Quelque chose a-t-il changé récemment dans WP qui affecterait cettefonctionnalité?Pour une raison quelconque,je n'aipas de données `$ _POST` aumoment oùj'arrive à`my_ajax_upload`,même si dans le callback JS `showRequest` leparamètre`formData` contienttout ce quej'attends.Has anything changed recently in WP that would affect this functionality? For some reason I have no `$_POST` data by the time I get to `my_ajax_upload`, even though in the JS callback `showRequest` the `formData` param contains everything I expect.
- 0
- 2013-01-04
- drzaus
-
Bizarrement,sije change laméthode duformulaireen "GET",ilfaittoujours unmessagemais avec les détails duformulaire dans l'URL,et cen'est qu'alors que les données duformulaire sont disponibles côté serveur (bien qu'entant queparamètres d'URL).* Mise àjour: * Sauf lesfichiers :)Weirdly, if I change the form method to "GET", it still does a post but with the form details in the URL, and only then is the form data available server-side (albeit as URL params). *Update:* Except the files :)
- 0
- 2013-01-04
- drzaus
-
@Bainternet,solutiongéniale.Lafonction de rappel deposte (showResponse)ne fonctionnepas.Avez-vous des suggestionspour cela?@Bainternet , Awesome solution.The post call back function(showResponse) is not working.Do you have any suggestions for that?
- 0
- 2015-01-27
- Rocker Maruf
-
Cane fonctionnepas?deserreurs?not working? any errors?
- 0
- 2015-01-28
- Bainternet
Nous souhaitons que les utilisateurspuissenttélécharger la vignette de l'article lors de lamodification des articles.Comment cela seferait-il?J'imagine qu'il utiliserait lesfonctions ajax de wordpress.
Toutes lesidées,
Merveilleux