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

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

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

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

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

<?php
// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );
$wordpress_upload_dir = wp_upload_dir();
// $wordpress_upload_dir['path'] is the full server path to wp-content/uploads/2020/11, for multisite works good as well
// $wordpress_upload_dir['url'] the absolute URL to the same folder, actually we do not need it, just to show the link to file
$i = 1; // number of tries when the file with the same name is already exists
 
$profilepicture = $_FILES['profilepicture'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
 
if( empty( $profilepicture ) )
	die( 'File is not selected.' );
 
if( $profilepicture['error'] )
	die( $profilepicture['error'] );
 
if( $profilepicture['size'] > wp_max_upload_size() )
	die( 'It is too large than expected.' );
 
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
	die( 'WordPress doesn\'t allow this type of uploads.' );
 
while( file_exists( $new_file_path ) ) {
	$i++;
	$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
 
// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
	$upload_id = wp_insert_attachment( array(
		'guid'           => $new_file_path, 
		'post_mime_type' => $new_file_mime,
		'post_title'     => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
		'post_content'   => '',
		'post_status'    => 'inherit'
	), $new_file_path );
 
	// wp_generate_attachment_metadata() won't work if you do not include this file
	require_once( ABSPATH . 'wp-admin/includes/image.php' );
 
	// Generate and save the attachment metas into the database
	wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
 
	// Show the uploaded file in browser
	wp_redirect( $wordpress_upload_dir['url'] . '/' . basename( $new_file_path ) );
}

原文链接:https://www.dqzy.cn/2025/04/23/471.html,转载请注明出处。 1、本站所有源码资源(包括源代码、软件、学习资料等)仅供研究学习以及参考等合法使用,请勿用于商业用途以及违法使用。如本站不慎侵犯您的版权请联系我们,我们将及时处理,并撤下相关内容! 2、访问本站的用户必须明白,本站对所提供下载的软件和程序代码不拥有任何权利,其版权归该软件和程序代码的合法拥有者所有,请用户在下载使用前必须详细阅读并遵守软件作者的“使用许可协议”,本站仅仅是一个学习交流的平台。 3、如下载的压缩包需要解压密码,若无特殊说明,那么文件的解压密码则为:www.dqzy.cn。 4、点启资源网是一个免费且专业分享网站源码、图片素材、特效代码、教程文章、站长工具的平台。我们努力给站长提供好的资源!
0

评论0

请先
显示验证码
没有账号?注册  忘记密码?