将FILE_GET_CONTENTS与重力表单一起使用上载文件夹在媒体库中创建图像,返回FALSE

时间:2020-11-11 作者:Kirsty Marks

我正在使用Gravity表单,它正在上传媒体并通过https将图像重新创建到相关的媒体文件夹中。

但是,在我的服务器上,这似乎没有正确读取Gravity文件夹或图像的内容。正在创建文件,但没有来自图像的数据。(我在下面包含了我的完整上传代码。我发现一篇文章“file\\u get\\u contents”在本地SSL方面存在问题,这似乎在本地正常工作。

感谢您的想法/指导

(注意,Prefix只是一个附加参数,显然$imgArr是一个图像URL数组,我从Gravity表单一个接一个地传递它。)

json_encode($entity[x])

名称来自重力表单中的另一个变量,也是一个实体。

提前谢谢你。

function createImage($prefix, $imgArr, $name){

    $i = 1;
    //Sorting out the URLs prior to creation
    foreach($imgArr as $url) {

            $finalUrl = str_replace(\'""\', \'\',$url);
            $newName = $name . $prefix . \'-\'. $i;
            $i++;


            $arrContextOptions=array(
                "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
                ),
            );

            $upload_dir = wp_upload_dir();
            $image_data = file_get_contents($finalUrl, false, stream_context_create($arrContextOptions));

            //Strip out the old filename and replace with the befores name
            $slash = strrpos($finalUrl, \'/\', 0);
            $slash++;
            $fileName = array_pop(str_split($finalUrl, $slash));
            $fileExt =  array_pop(explode(\'.\', $fileName));
            $newFileName = $newName . \'.\' . $fileExt;

            if(wp_mkdir_p($upload_dir[\'path\']))
                $file = $upload_dir[\'path\'] . \'/\' . $newFileName;
            else
                $file = $upload_dir[\'basedir\'] . \'/\' . $newFileName;
            file_put_contents($file, $image_data);

            $wp_filetype = wp_check_filetype($newFileName, null);
                $upload_id = array(
                    \'post_mime_type\' => $wp_filetype[\'type\'],
                    \'post_title\'=> sanitize_file_name($newFileName),
                    \'post_content\'   => \'\',
                    \'post_status\'    => \'inherit\'
            );

            $attach_id = wp_insert_attachment( $upload_id, $file, $post_ID);

            if (!is_wp_error($attach_id)) {
                require_once( ABSPATH . \'wp-admin/includes/image.php\' );
                $attachment_data = wp_generate_attachment_metadata( $attach_id,  $file );
                wp_update_attachment_metadata( $attach_id,  $attachment_data );
                set_post_thumbnail( $post_ID, $attachment_data );
            }

            //Return the uploaded image ID, so to use to update the ACF field

    }
}

1 个回复
SO网友:joshmoto

我在你的评论中注意到。。。

返回上载的图像ID,以便用于更新ACF字段

这里有两个函数可以帮助您解决。。。

  • gf_handle_attachments() 将gform提交图像文件转换为wordpress媒体附件。正在返回媒体(附件)id。
  • gf_upload_to_media_acf() 处理gform提交的图像或多个图像,并使用媒体附件更新定义的acf(图像、文件或库)字段
文件类型jpeg, jpg, png, 和gif 仅在我测试过的情况下才适用。文件类型pdf 不喜欢添加到acfimagegallery 字段。这个pdf 仍会添加,但WordPress会添加not 创建任何预览。

$filename 参数不仅仅是文件名,它是通过httpshttp. 基本上gform提交的协议。

以下是gf_handle_attachments() 处理转换单个$filename 进入wordpress媒体附件。返回附件id。

// save image to media library and then save the image to acf field
function gf_handle_attachments($filename, $parent_post_id) {

    // check the type of file
    // we\'ll use this as the \'post_mime_type\'
    $file_type = wp_check_filetype( basename( $filename ), null );

    // get the path to the upload directory
    $wp_upload_dir = wp_upload_dir();

    // prepare an array of attachment post data
    $attachment = [
        \'guid\'           => $wp_upload_dir[\'url\'] . \'/\' . basename( $filename ),
        \'post_mime_type\' => $file_type[\'type\'],
        \'post_title\'     => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
        \'post_content\'   => \'\',
        \'post_status\'    => \'inherit\'
    ];

    // insert the attachment
    $attach_id = wp_insert_attachment($attachment, $filename, $parent_post_id);

    // make sure that this file is included, as wp_generate_attachment_metadata() depends on it
    require_once( ABSPATH . \'wp-admin/includes/image.php\' );

    // generate the metadata for the attachment, and update the database record
    $attach_data = wp_generate_attachment_metadata($attach_id,$filename);
    wp_update_attachment_metadata($attach_id, $attach_data);

    // delete file from gf uploads
    //unlink($filename);

    // return attachment id
    return $attach_id;

}
这是gf_upload_to_media_acf() 接受提交的gfrom文件上载或gfrom多文件上载条目的函数$value 并将它们添加到定义的acf(图像、文件或库)$field 已定义为$post_id.

// upload gf uploads media to post acf field
function gf_upload_to_media_acf($value, $post_id, $field) {

    // if entry value begins with json brackets (gfrom multi-file upload entry)
    if(substr($value,0,2) === \'["\') {

        // decode gfrom entry value into array
        $filenames = json_decode(stripslashes($value));

        // lets begin multiple attachment array
        $attach_ids = [];

        // for each filenames as filename
        foreach ($filenames as $filename) {

            // handle each filename to wordpress media attachment linked to post
            $attach_ids[] = gf_handle_attachments($filename, $post_id);

        }

        // update acf (gallery) field with the attachment ids
        update_field($field, $attach_ids, $post_id);

    // else if single gform image upload entry
    } else {

        // handle single media attachment and return attachment id
        $attach_id = gf_handle_attachments($value, $post_id);

        // update acf (image, file or gallery) field for post with the attachment id
        update_field($field, $attach_id, $post_id);

    }

}
以下是使用gform_confirmation 创建新帖子并使用update_entry_data_fields() 函数传递条目数据,然后处理指定的条目字段(文件上载)。。。

// filter to fire when gfrom id 1 hits confirmation
add_filter(\'gform_confirmation_1\', \'form_confirmation\', 10, 4 );

// form confirmation function for above gform filter
function form_confirmation($confirmation, $form, $entry, $ajax) {

    // new post settings array
    $post = [
        \'post_type\'     => \'post\',
        \'post_status\'   => \'pending\'
    ];

    // create new post for our submission using post array settings and return the newly created post id to result variable
    $result = wp_insert_post($post);

    // if result post id and is not a wp_error then...
    if($result && !is_wp_error($result)) {

        // get the created result post id
        $post_id = $result;

        // create our post title
        $title = \'Post #\' . $post_id;

        // new submission array to use to update the created post
        $submission = [
            \'ID\'            => $post_id,
            \'post_title\'    => $title,
            \'post_name\'     => sanitize_title($title)
        ];

        // update the created submission post with new submission array data
        wp_update_post($submission);

        // update this post acf fields with entry data
        update_entry_data_fields($post_id, $entry);

        // return submission post id if you wana 
        return $post_id;

    }

    // return false
    return false;

}

update_entry_data_fields() 函数是我们使用的地方gf_upload_to_media_acf() 用于gform提交文件上载条目数据的函数。。。

// update acf fields or anything else for defined post id using gform submission entry array data
function update_entry_data_fields($post_id, $entry) {

    // if form submission entry is array
    if(is_array($entry)) {

        // for each entry item
        foreach ($entry as $key => $value) {

            // if entry key is our gform file upload or multi-file upload entry field
            if($key === \'1.8\') {

                // if we have a entry value
                if($value) {

                    // image, file or gallery acf field name
                    $acf_field = \'acf_field_name\';

                    // handle the media attachment(s) creation and add attachment(s) to acf (image, file, or gallery) field via acf_field_name
                    gf_upload_to_media_acf($value, $post_id, $acf_field);

                }

            }

        }

    }

}