0

我有一个有多个页面的重力表单,并且在至少 3 个页面上有一个多文件上传字段。我正在尝试从每个字段中获取上传的项目,并自动将它们添加到媒体库以进行进一步操作。使用此解决方案,我可以从第一页获取文件并将它们上传到媒体库,但是,我无法弄清楚如何从其他两页获取文件。

下面是我的代码片段。如果我调整$submit = $entry["4"];多上传的字段 ID 以包含其他上传字段,它会破坏我的foreach()声明,说invalid argument is supplied.

我还尝试添加其他$submit部分以包含其他字段 id,但它只需要最后一个字段 id 条目。多次添加这整段代码也不起作用,因为它是相同的形式,只是不同的页面,我得到:

致命错误:无法重新声明 copy_post_image2()(之前在 ...\functions.php 中声明

//Multi-file upload code: upload multiple files through Gravity Forms and have them automatically moved to the WordPress Media Library
add_filter("gform_after_submission_1", "my_add_post_attachments",10,2); //Your form ID
function my_add_post_attachments($entry, $form){


$submit = array();
$submit = $entry["4"]; //The field ID of the multi upload
$submit = stripslashes($submit);
$submit = json_decode($submit, true);

foreach ($submit as $key => $value){

require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
$post_id = 200; //The post ID of the page you are adding images
$url = $value;

$file = copy_post_image2($url, $post_id);

if(!$file)
return false;

$name = basename($url);
$name_parts = pathinfo($name);
$name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );

$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = $name;
$content = '';

$attachment = array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
);

$id = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($id) ) {
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}
}
}

function copy_post_image2($url, $post_id){
$time = current_time('mysql');

if ( $post = get_post($post_id) ) {
if ( substr( $post->post_date, 0, 4 ) > 0 )
$time = $post->post_date;
}

//making sure there is a valid upload folder
if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
return false;

$name = basename($url);

$filename = wp_unique_filename($uploads['path'], $name);

// Move the file to the uploads dir
$new_file = $uploads['path'] . "/$filename";

$uploaddir = wp_upload_dir();
$path = str_replace($uploaddir["baseurl"], $uploaddir["basedir"], $url);

if(!copy($path, $new_file))
return false;

// Set correct file permissions
$stat = stat( dirname( $new_file ));
$perms = $stat['mode'] & 0000666;
@ chmod( $new_file, $perms );

// Compute the URL
$url = $uploads['url'] . "/$filename";

if ( is_multisite() )
delete_transient( 'dirsize_cache' );

$type = wp_check_filetype($new_file);
return array("file" => $new_file, "url" => $url, "type" => $type["type"]);

}

任何有关如何添加额外的多文件上传字段的建议将不胜感激。

4

1 回答 1

0

根据错误,您可能会copy_post_image2两次声明该函数。我没有看到它在您共享的代码中列出了两次,但是如果您在 functions.php 文件中搜索它,我敢打赌您会找到它的第二个副本。

至于从所有页面上的所有文件上传字段复制所有图像的最终目标,请查看Gravity Forms Media Library。它会像魔术一样处理这个问题,并支持通过合并标签以不同大小显示图像。

于 2021-02-17T13:40:43.143 回答