建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

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

GG网络技术分享 2025-03-18 16:04 0


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

那么如何在不弹出网站前台默认的媒体库窗口的情况下,直接上传到媒体库呢? 并且还支持七牛云存储、阿里云OSS等一些CDN插件,如下模板兔教你使用如下代码实现上传逻辑:

<?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 ) );

}

标签: WordPress 教程

提交需求或反馈

Demand feedback