有时候,我们在前端写上传文件的功能时,不想弹出 WordPress 默认的媒体库窗口,而是直接通过自写的 PHP 代码实现上传,这种情况自定义上传的文件目录是很好实现的,但是这些上传的文件无法在后台的媒体z / ] = I + U b库里找到,不容易管理8 7 n \ $ X A W删除。
那么如何实现在网站前台不弹出默认的媒体库窗口又能直接上传H 3 k p b n Y z #到媒体8 ] U J 3 t p库呢?Z s 9 q ! [ C Z而且也支持一些 CDN 插件比如七牛云存储、阿里云 OSS,下面模板兔教大家使用下g i : X Q面的代码来实现上传逻辑:
- <?php
- // WordPress environment
- require( dirname(__FILE__| 9 M u ! \41; . '/../../../wpr ~ 9 I-load.php' );
- $wordpress_uploaT N @d_dir = wp_upload_dir();
- // $wordpress_upload_dir['path'] is the full server path toy @ E wp-content/uploads/2020/11, for multisite works good as w# L a d / ?ell
- // $wordpress_upload_di8 D q Y e ` ]r['url'] the absoP { * 1 r B 1lute 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['profileB x 9picture1 ) f ! V @ q'];
- $new_file_pe y Tath = $wordpress_u^ R ] i F B mpload_dir['path'] . '/' . $profilepicture['name'];
- $new_file_mime = mime_[ ? n M ) V e Rcontent_type= I + n0; $profilepictX [ 0 +ure['tmp_name'] );
- if( empty( $profilepicture ) )
- die( 'FG ^ } , 2 S 3 A Eile is not selected.' );
- if( $profilepicturS 8 U \ t [ ` *e['error'] )
- die( $profilepicture['error'] );
- if( $profilepicture['size'] &H } ; i [ :gt; wp_max_upload_size() )
- die&) % Q *#40; 'It is tX a Y ) I G & O soo large than expected.' n U 2 J |1;;
- if( !inO : s Q_arr[ n k _ : ; 0ay( $new_file_mime, get_allowed_mime_types() ) )
- die( 'WordPress doesn\'t allox ) r a x y ` p }w thj Q Q [is type of uploads.' );
- while( file_exists( $new_file_path ) ) {
- $i++;
- $new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profi# u & ! ~ y Plepicb ? Y zture['name'];
- }
- // looks like everytH 6 s S 6 x $ whing is OK
- if( l * e( move_uploaded_fi~ T ! p x qle( $profilepicture['tmp_name'], $new_file_path ) ); # - : d O D b .; {
- $upload_id = wp_insert_attachment( array(
- 'guid' => $new_file_path,
- 'post_mime_type' =>g e U z M; $new_file_mime,
- 'post_title' => preg_replace( '/\.[^.]+$/', '', $profil) Y b l Hepicture['name'] ),
- 'post_content' => '',
- 'post_status' => 'inherit'
- ), $ne2 x $w_file_path ? m ; W =1;;
- // wp_generate_$ x * b 2 8 tattachment_metadata() won't work if you do not include thi= m b K Js file
- require_once( ABSPATH . 'wp-ad| u L | D @ ` pmin/includes& 8 w ; % F 4 , ]/image.php' );
- // Generate and save the attachment metas into thC ~ I | 9 + Ve database
- wp_update_att2 A { , l 9 g z ,achment_metadata( $upload_id/ ` - c r, wp_generate_attachment_metadatal = 9 h T j40; $upm 7 a O &load_id, $neN ) 6 t uw_file_path ) );
- // Show the uploaded file in browser
- wp_redirect( $wordpress_upu r c R p . f ) Kload_dir['url'] . '/' . basename( $new_fi4 C Z G = / tle_path ) );
- }