如何通过自定义字段创建文件上传域

时间:2020-10-28 作者:vishal

我正在尝试使文件上传字段提前自定义字段插件,我在ACF上找到了许多参考代码\'https://www.advancedcustomfields.com/resources/file/,堆栈溢出,堆栈交换WordPress开发,我还参考了WP Begginer,kinsta。但他们给出了插件的解决方案,比如如何使用WP表单插件。我想让它没有插件通过自定义字段。如果有人知道,请给出你有价值的建议。

1 个回复
SO网友:Hendrik Vlaanderen

您需要在表单、php文件和JS中添加以下内容。

密切关注这种方法,因为它不适合你。我正在自定义字段中存储文件URL。可能您更喜欢另一种存储文件的方式。

首先,需要添加两个HTML输入字段。将输入类型文件以及隐藏字段添加到表单中

<input class="input_file" type="file" id="file" name="input_file" />
<input type="hidden" class="hidden-file-field" name="hidden_file_field" />
js在这里,我们检查文件字段的更改并执行ajax请求。请注意;“全球”;变量名,因为它实际上是在下面PHP的localize\\u脚本中设置的。

这里的主要策略实际上是将文件保存在一个隐藏字段中,稍后将在表单中提交该字段。

    $imgFile.on(\'change\', function(e) {
    
        e.preventDefault();

        var data = new FormData();

        var files = $(\'input[name="input_file"]\').prop(\'files\')[0];
        data.append(\'input_file\', files);

        data.append(\'nonce\', global.nonce);
        data.append(\'action\', \'media_upload\')
        var data_type = \'image\';

        jQuery.ajax({
            url: global.ajax,
            data: data,
            processData: false,
            contentType: false,
            dataType: \'json\',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();

                if ( myXhr.upload ) {
                    myXhr.upload.addEventListener( \'progress\', function(e) {

                    }, false );
                }

                return myXhr;
            },
            type: \'POST\',
            beforeSend: function() {
                // handle before send
            },
            success: function(resp) {
                // handle success
                // Save the result the url or attachment ID in a hidden input field and when the overall form is submitted, save it in the custom field.

                $(\'.hidden-file-field\').val(resp.url)



            }
        });

    })
PHP:我们首先需要包含一个用于提交媒体字段的nonce,然后我们需要具有实际上载文件数据并返回url和其他一些数据的功能。这是通过针对ajax提交的add\\u操作完成的。

   // Localize script is needed to have the nonce included
   wp_localize_script(

        \'jsfilename\',
        \'global\',
        array(
            \'ajax\' => admin_url( \'admin-ajax.php\' ),
            \'nonce\'      => wp_create_nonce(\'media-form\')
        )
    );
add_action( \'wp_ajax_media_upload\', \'media_upload\' );
add_action( \'wp_ajax_nopriv_media_upload\', \'media_upload\');


function media_upload(){

    if ( check_ajax_referer( \'media-form\', \'nonce\', false ) == false ) {
        wp_send_json_error(array(\'error\' => \'nonce failed\'));
    }

    require_once(ABSPATH . \'wp-load.php\');


    if (isset($_FILES[\'input_file\'] ) && !empty($_FILES[\'input_file\'][\'name\']) )
    {
        $allowedExts = array("doc", "docx", "pdf");


        $temp = explode(".", $_FILES["input_file"]["name"]);
        $extension = end($temp);
        if ( in_array($extension, $allowedExts))
        {
            if ( ($_FILES["input_file"]["error"] > 0) && ($_FILES[\'input_file\'][\'size\'] <= 3145728 ))
            {
                $response = array(
                    "status" => \'error\',
                    "message" => \'ERROR Return Code: \'. $_FILES["input_file"]["error"],
                );
            }
            else
            {
                $uploadedfile = $_FILES[\'input_file\'];
                $upload_name = $_FILES[\'input_file\'][\'name\'];
                $uploads = wp_upload_dir();
                $filepath = $uploads[\'path\']."/$upload_name";

                if ( ! function_exists( \'wp_handle_upload\' ) )
                {
                    require_once( ABSPATH . \'wp-admin/includes/file.php\' );
                }
                require_once( ABSPATH . \'wp-admin/includes/image.php\' );
                $upload_overrides = array( \'test_form\' => false );
                $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
                if ( $movefile && !isset( $movefile[\'error\'] )  ) {

                    $file = $movefile[\'file\'];
                    $url = $movefile[\'url\'];
                    $type = $movefile[\'type\'];

                    $attachment = array(
                        \'post_mime_type\' => $type ,
                        \'post_title\' => $upload_name,
                        \'post_content\' => \'File \'.$upload_name,
                        \'post_status\' => \'inherit\'
                    );

                    $attach_id = wp_insert_attachment( $attachment, $file, 0);
                    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                    wp_update_attachment_metadata( $attach_id, $attach_data );

                }

                $response = array(
                    "status" => \'success\',
                    "url" => $url,
                    "attachment_id" => $attach_id
                );

            }
        }
        else
        {
            $response = array(
                "status" => \'error\',
                "message" => \'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini\',
            );
        }
    }

        wp_send_json_success($response);


}
最后,当您使用AJAX或普通帖子提交表单时,您应该使用下面的内容。最有可能的是,您将首先清理$POST。我让你来决定:

update_field(\'name_of_file_field\', $POST[\'hidden_file_field\'] $post_id);

相关推荐