出于某种原因,我从一开始就一直在使用的代码似乎已停止在我的开发环境中工作,该环境是在免费托管服务上设置的。但是,它仍然在本地工作。现在,我不记得我是否曾经在开发环境中进行过实际测试,所以也许它从未在那里开始工作。
基本上,我使用Gravity Forms创建自定义帖子(工作得很好),并且我还使用多个文件上传来添加图片附件到帖子。由于这并不完全支持GF,但我摆弄并设法在这里创建这个小功能:
function create_post_attachment_from_gf($f, $from_url) {
//for image field, it sends content with a bunch of other parameters in a string with pipe delimiters
$split_image = explode('|', $from_url);
if( count($split_image) > 0 )
$from_url = $split_image[0];
if( !empty( $_FILES[$f]['name'] ) ) {
$file = $_FILES[$f];
$uploads = wp_upload_dir( null );
$filename = wp_unique_filename( $uploads['path'], $file['name'], null );
// Strip the query strings.
$filename = str_replace('?','-', $filename);
$filename = str_replace('&','-', $filename);
// Compute the URL
$url = $uploads['url'] . "/$filename";
$new_file = $uploads['path'] . "/$filename";
copy($from_url,$new_file);
// Move the file to the uploads dir
$stat = stat( dirname( $new_file ));
$perms = $stat['mode'] & 0000666;
@ chmod( $new_file, $perms );
return array( 'file' => $new_file, 'url' => $url, 'type' => $file['type'], 'name' => $file['name'] );
}
return false;
}
然后以这种方式调用它来创建附件:
$copied_file = create_post_attachment_from_gf('input_' . $file_uploads[$i], $entry[$file_uploads[$i]]);
$subdir = wp_upload_dir( null )["subdir"];
if( $copied_file ){
$attachment = array(
'guid' => $copied_file['url'],
'post_mime_type' => $copied_file['type'],
'post_title' => $copied_file['name'],
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $subdir . '/' .$copied_file['name'], $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $copied_file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
看起来这里的副本失败了。它在我的uploads文件夹中使用正确的文件名创建一个空文件。我检查了我的文件夹权限,甚至继续将上传内容(包括重力形式文件夹)设置为777,但由于某种原因它仍然无效。
我的本地和远程网站都在WP 3.8.1上运行,所有插件都是最新的。除了一些不应该干扰它的测试数据之外,数据库几乎完全相同。直接从仪表板添加附件工作正常。这是我应该与托管公司讨论的事情吗?或者我的代码有问题吗?或者也许有一种方法可以在不移动文件的情况下创建附件 - 这对我来说没问题。
感谢任何帮助。
答案 0 :(得分:0)
嗯,看起来,虽然复制仍然无法远程操作,但我可以将图像从开始直接上传到正确的文件夹。
//Have gform upload directly in the upload folder
add_filter("gform_upload_path", "change_upload_path", 10, 2);
function change_upload_path($path_info, $form_id){
$uploads = wp_upload_dir( null );
$path_info["path"] = $uploads['path'] . "/";
$path_info["url"] = $uploads['url'] . "/";
return $path_info;
}
所以我删除了移动文件的部分并从我之前的函数中重新创建了文件名,一切都按计划进行。简直不敢相信我花了几个小时......希望这有助于其他人吗?