WordPress教程

WordPress 如何在前端自定义上传图片文件到媒体库

也想出现在这里?联系我们
创客云

有时候,我们在前端写上传文件的功能时,不想弹出 wordpress 默认的媒体库窗口,而是直接通过自写的 PHP 代码实现上传,这种情况自定义上传的文件目录是很好实现的,但是这些上传的文件无法在后台的媒体库里找到,不容易管理删除。

那么如何实现在网站前台不弹出默认的媒体库窗口又能直接上传到媒体库呢?而且也支持一些 CDN 插件比如七牛云存储、阿里云 OSS,下面模板兔教大家使用下面的代码来实现上传逻辑:

也想出现在这里?联系我们
创客主机
  1. <?php
  2. // WordPress environment
  3. require( dirname(__FILE__) . '/../../../wp-load.php' );
  4. $wordpress_upload_dir = wp_upload_dir();
  5. // $wordpress_upload_dir['path'] is the full server path to wp-content/uploads/2020/11, for multisite works good as well
  6. // $wordpress_upload_dir['url'] the absolute URL to the same folder, actually we do not need it, just to show the link to file
  7. $i = 1; // number of tries when the file with the same name is already exists
  8.  
  9. $profilepicture = $_FILES['profilepicture'];
  10. $new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
  11. $new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
  12.  
  13. if( empty( $profilepicture ) )
  14. 	die( 'File is not selected.' );
  15.  
  16. if( $profilepicture['error'] )
  17. 	die( $profilepicture['error'] );
  18.  
  19. if( $profilepicture['size'] > wp_max_upload_size() )
  20. 	die( 'It is too large than expected.' );
  21.  
  22. if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
  23. 	die( 'WordPress doesn\'t allow this type of uploads.' );
  24.  
  25. while( file_exists( $new_file_path ) ) {
  26. 	$i++;
  27. 	$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
  28. }
  29.  
  30. // looks like everything is OK
  31. if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
  32. 	$upload_id = wp_insert_attachment( array(
  33. 		'guid'           => $new_file_path, 
  34. 		'post_mime_type' => $new_file_mime,
  35. 		'post_title'     => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
  36. 		'post_content'   => '',
  37. 		'post_status'    => 'inherit'
  38. 	), $new_file_path );
  39.  
  40. 	// wp_generate_attachment_metadata() won't work if you do not include this file
  41. 	require_once( ABSPATH . 'wp-admin/includes/image.php' );
  42.  
  43. 	// Generate and save the attachment metas into the database
  44. 	wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
  45.  
  46. 	// Show the uploaded file in browser
  47. 	wp_redirect( $wordpress_upload_dir['url'] . '/' . basename( $new_file_path ) );
  48. }
也想出现在这里?联系我们
创客主机
服务范围 1、专业提供WordPress主题、插件汉化、优化、PHP环境配置等服务请详询在线客服
2、本站承接 WordPress、DedeCMS、ThinkPHP 等系统建站、仿站、开发、定制等服务
3、英文模板(主题)安装费用为120元/次,汉化主题首次免费安装(二次安装30元/次)
售后时间 周一至周五(法定节假日除外) 10:00-22:00
(1)

本文由 云模板 作者:PetitQ 发表,转载请注明来源!

也想出现在这里?联系我们
创客主机

热评文章

发表评论

热销模板

高端信息技术产品展示DedeCMS织梦中英文模板

Envato

本站承接 WordPress / DedeCMS / ThinkPHP 等
系统建站、仿站、开发、定制等业务!