ACF.Как обновить поле повторителя с файлами? - PullRequest
0 голосов
/ 27 февраля 2019

Я пытаюсь обновить поле моего репитера из файлов переднего плана.В случае с одним полевым файлом - работает.Но когда я пытаюсь заполнить ретранслятор файлами, это не работает.

// JS. Ajaxly sending files
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';

$('.js-new-msg-send').click(function (e) {

    e.preventDefault();
    var form = document.forms.namedItem("new_theme");

    var formData = new FormData(form);
    formData.append('user_id', '<?php echo $userID; ?>');
    formData.append('action', 'msg_to_acf');

    var xhr = new XMLHttpRequest();
    xhr.open('POST', ajaxurl, true);
    xhr.send(formData);

})

Я нашел функцию для обработки файлов, загружаемых в поле acf, и изменил ее для обработки нескольких файлов из переменной $ _FILES:

// FOR MULTIPLE FILES 
if ( !empty($_FILES[$f]['name']) && is_array($_FILES[$f]['name']) ) {

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

    $file_list = array();
    foreach ($_FILES[$f]['name'] as $key => $value) {
        $temp_file = array(
            'name'     => $_FILES[$f]['name'][$key],
            'type'     => $_FILES[$f]['type'][$key],
            'tmp_name' => $_FILES[$f]['tmp_name'][$key],
            'error'    => $_FILES[$f]['error'][$key],
            'size'     => $_FILES[$f]['size'][$key]
        );

        wp_update_attachment_metadata( $pid, $temp_file );
        $file = wp_handle_upload( $temp_file , array('test_form' => FALSE, 'action' => 'editpost') );
        if ( isset( $file['error'] )) {
        return new WP_Error( 'upload_error', $file['error'] );
        }
        $file_type = wp_check_filetype($temp_file['name'], array(
            'jpg|jpeg' => 'image/jpeg',
            'gif' =>      'image/gif',
            'png' =>      'image/png',
        ));


        if ($file_type['type']) {

            $name_parts = pathinfo( $file['file'] );
            $name = $file['filename'];
            $type = $file['type'];
            $title = $t ? $t : $name;
            $content = $c;

            $attachment = array(
                'post_title' => $title,
                'post_type' => 'attachment',
                'post_content' => $content,
                'post_parent' => $pid,
                'post_mime_type' => $type,
                'guid' => $file['url'],
            );

            foreach( get_intermediate_image_sizes() as $s ) {
                $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
                $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
                $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
                $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
            }

            $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );

            foreach( $sizes as $size => $size_data ) {
                $resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
                if ( $resized )
                $metadata['sizes'][$size] = $resized;
            }

            $attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);

            if ( !is_wp_error( $id )) {
                $attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
                wp_update_attachment_metadata( $attach_id, $attach_meta );
            }

            $final_temp_arr = array(
                'pid' =>$pid,
                'url' =>$file['url'],
                'file'=>$file,
                'attach_id'=>$attach_id
            );
            array_push($file_list, $final_temp_arr);    
        }
    }
    return $file_list;
}

В заключение я использовал эту функцию, чтобы получитьмассив информации с переменной attach-id , которую я вставил в повторитель.

        $att = my_update_attachment( 'msg-file-list' , $post_id );
        $files_final_list = array();
        foreach ($att as $key => $val) {
            array_push($files_final_list, $val['attach_id']);
        }
        $value_arr = array(
            array(
                "msg-author"     => $user_name,
                "msg-date"       => $date,
                "msg-read-check" => true,
                "msg-cont"       => $msg_cont,
                'msg-file-list'  => $files_final_list
            )
        );
        update_field( 'test_file_list' , $files_final_list , $post_id );

Я предполагаю, что ошибка в последней части, где я пытаюсь загрузить файлы в ретранслятор.Может кто-нибудь показать мне, что я делаю не так?Спасибо за помощь.

...