问题在于:我正在尝试将多个客户上传的图片添加到woocommerce产品订单中。
这是我当前的功能在添加购物车按钮之前生成字段的方式(这显示正确并允许客户从他们的计算机中选择要上传的文件):
function my_special_fields(){
if (get_the_title() == "My Special Product"){
echo '<table>
<tbody>
<tr>
<td>
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
</td>
</tr>
</tbody>
</table>';
}
}
我用钩子打电话:
add_filter('woocommerce_before_add_to_cart_button', 'my_special_fields');
然后我使用另一个钩子将项目数据添加到购物车:
add_action( 'woocommerce_add_cart_item_data', 'save_my_special_fields', 10, 2 );
使用该钩子调用的函数如下所示:
function save_my_special_fields( $cart_item_data, $product_id ) {
// I save a lot of fields in here that are working fine so ignoring those for now
// This is where I try and find my file to upload
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file );
}
}
}
}
它将我发现的用于上传文件的代码调用到wordpress:https://hugh.blog/2014/03/20/wordpress-upload-user-submitted-files-frontend/
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
现在我没有分配任何帖子或对图像做任何事情而不是试图让它上传,以便作为管理员我可以在我的媒体文件夹中查看它。
我认为问题是添加到购物车字段的woocommerce表单可能没有这种编码:
enctype="multipart/form-data
任何帮助实现这一点而不需要额外的woocommerce插件将非常感激。