wp_mail, Dynami c вложение изображений с компьютера с несколькими полями, загружая одно изображение - PullRequest
0 голосов
/ 29 марта 2020

Я знаю, что это дублирующий вопрос, но, пожалуйста, будьте добры со мной, я должен решить это. У меня есть пользовательская форма в Wordpress, отправляющая шаблон электронной почты через AJAX. Все работает нормально, за исключением тех вложений отдельных полей на изображении ниже. эти поля ввода запускаются jquery для получения изображения, и я проверил, не является ли файл ввода формы пустым с Jquery перед отправкой электронного письма. Когда я ставлю жесткий код, он работает, в противном случае это не так. Пожалуйста, направьте меня, чтобы решить это. Любая помощь будет признателен за мою HTML форму:

              <form id="tratamento_form"  method="POST" action="#" enctype="multipart/form-data">

                 <div class="form-group ">
                     <label for="name" class="">Nome completo</label>
                     <input id="name" class="form-control  " placeholder="José Aparecido " type="text" name="nome" id="name" autocomplete="off">
                 </div>
              

                 <div class="form-group ">
                   <label for="message" class="" >Selecione 6 fotos</label>
                    <div class="row">
                      <div class="col-sm-4">
                        <input type="file" id="real-file" name="img1" hidden="hidden" />
                        <div class="upload_btn_style">
                          <button type="button" id="custom-button"><i class="fas fa-plus"></i></button>
                          <span id="custom-text">Enviar foto (jpg, png)</span>
                        </div>
                      </div>

                      <div class="col-sm-4">
                         <input type="file" id="real-file1" name="img2" hidden="hidden" />
                         <div class="upload_btn_style">
                           <button type="button" id="custom-button1"><i class="fas fa-plus"></i></button>
                           <span id="custom-text1">Enviar foto (jpg, png)</span>
                         </div>
                      </div>

                      <div class="col-sm-4">
                         <input type="file" id="real-file2" name="img3" hidden="hidden" />
                         <div class="upload_btn_style">
                           <button type="button" id="custom-button2"><i class="fas fa-plus"></i></button>
                           <span id="custom-text2">Enviar foto (jpg, png)</span>
                         </div>
                      </div>
                    </div>
                 </div>

                 <input type="file" id="testfile" name="tesinput" value="">
                 <span id="custom-text12">Enviar foto (jpg, png)</span>

                 <div class="form-group ">

                    <div class="row">

                      <div class="col-sm-4">
                         <input type="file" id="real-file3" name="img4" hidden="hidden" />
                         <div class="upload_btn_style">
                           <button type="button" id="custom-button3"><i class="fas fa-plus"></i></button>
                           <span id="custom-text3">Enviar foto (jpg, png)</span>
                         </div>
                      </div>

                      <div class="col-sm-4">
                         <input type="file" id="real-file4" name="img5" hidden="hidden" />
                         <div class="upload_btn_style">
                           <button type="button" id="custom-button4"><i class="fas fa-plus"></i></button>
                           <span id="custom-text4">Enviar foto (jpg, png)</span>
                         </div>
                      </div>

                      <div class="col-sm-4">
                         <input type="file" id="real-file5" name="img6" hidden="hidden" />
                         <div class="upload_btn_style">
                           <button type="button" id="custom-button5"><i class="fas fa-plus"></i></button>
                           <span id="custom-text5">Enviar foto (jpg, png)</span>
                         </div>
                      </div>
                    </div>
                 </div>


                 <div class="form-group ">
                     <input class="btn btn-primary btn-lg btn-block submit " value="Enviar " type="submit" name="button_submit" id="button_submit">
                 </div>
                 <!-- to be change Hidden value added for WordPress ajax security and to validate function name -->
                 <input type="hidden" name="action" value="field_action_for_ajax_tratamento"/>

                   <div class="msgs-formulario"></div>
                   <!-- Start success message -->
                 <div class="alert alert-success" id="success_message" role="alert">Mensagem enviada com sucesso <i class="far fa-thumbs-up"></i> Aguarde o nosso retorno!
                 </div>
            </form>

function contact_ajax_tratamento() {

    // This calls the javascript we just created for the form validation
    wp_localize_script( 'tratamento_ajax', 'wp_ajax', array(
        'tratamento' => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( "ajax_nonce" ) // this is a unique token to prevent form hijacking
    ) );

    // Enable any admin to run ajax_login() in AJAX and POST the form
    add_action( 'wp_ajax_field_action_for_ajax_tratamento', 'ajax_tratamento_form_process' );

    // Enable any user with no privileges to run ajax_login() in AJAX and POST the form
    add_action( 'wp_ajax_nopriv_field_action_for_ajax_tratamento', 'ajax_tratamento_form_process' );
}

    // Initiate the ajax enquiry form and add the validation javascript file
    add_action( 'init', 'contact_ajax_tratamento' );
    add_action( 'wp_enqueue_scripts', 'contact_ajax_tratamento' );

// Function to send the email using the email template
function ajax_tratamento_form_process() {

  ob_start();

     // include THE MAIL TEMPLATE
     include('assets/template/tratamento.php');

     $message = ob_get_contents();
     ob_end_clean();
	 
// HARD CODE IMAGE
// $atachments = array( get_home_path() . '/wp-content/uploads/2020/03/Wedding.jpg');

          $uploadedfile = $_FILES['image'];

            $upload_overrides = array( "test_form" => false );

            $uploaded_file = wp_handle_upload ($file, $upload_overrides);

            if( isset( $uploaded_file ["image"] )) {
            	$file_name_and_location = $uploaded_file ["image"];
            	$file_title_for_media_library = $title;

            	$attachment = array(
            		"post_mime_type" => $uploaded_file_type,
            		"post_title" => addslashes( $file_title_for_media_library ),
            		"post_content" => "",
            		"post_status" => "inherit"
            	);

            	if( ! is_null( $post )) {
            		if ( ! is_numeric( $post )) {
            			$post = $post->ID;
            		} // if ()

            		$attachment ['post_parent'] = $post;
            	} // if ()

            	$id = wp_insert_attachment( $attachment, $file_name_and_location );

            	require_once( ABSPATH."wp-admin/includes/image.php" );

            	$attach_data = wp_generate_attachment_metadata( $id, $file_name_and_location );
            	wp_update_attachment_metadata( $id, $attach_data );
            } // if ()



     // $headers[] = 'Content-Type: text/html; charset=UTF-8';
     $headers[] =  'From: ' . trim( $_POST[ 'name' ] ) . ' <' . trim( $_POST[ 'email' ] ) . '>' . "\r\n";

     wp_mail('example@example.com', "FORMULARIO  TRATAMENTO - SUBJECT", $message, $headers, $atachments);

     $results['feedbacks'] = "All OK!";


     wp_send_json($results);
     die();

}

wordpress custom form

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...