the method to upload file in wordpress plugin developing
-
Recently,I was writing a wordpress plugin which will add a image to each tag.then my blog will have a pciture tag instead just text.I search google and baidu,can’t find a method to upload a file on my plugin setting page.there are many questions on the wordpress forum but I can not get a good answer.
I found out a plugin called wp_easy_uploader.after reading the code.I know how to upload files in wordpress.I will show the precedure below:
1.make a special submit form.
Generally we can upload file by creating a form include a file-type input,then php will send back a array and you can get
the file path like:
$_FILES[“fields”][“temp_name”]
But we can not do so in wordpress,because wordpress filter files.so,if you want upload a legal file,you shoude add a hidden input and write your form like this:1
2
3
4
5
6
7
8
<form enctype=”multipart/form-data” method=”post” action=”<?php $_SERVER[‘REQUEST_URI’]; ?>” >
<label>enter tags name:</label>
<input type=”text” name=”tagName” />
<label>chose a image:</label>
<input type=”file” name=”uploadFile” id=”uploadFile” />
<input type=”submit” value=”submit” name=”submit”/>
<input type=”hidden” name=”action” value=”wp_handle_upload” />
</form>
yes,it is necessary to add a hidden input named “action” and the value should be “wp_handle_upload”
2.make sense of the difference about $_FILES[“uploadFile”][“tmp_name”]
Once your submit your form,you can’t just get the temp file name by using $_FILES[“uploadFile”][“tmp_name”],because the value is not a file path string ,but a array of bits.yes,wordpress just read the file to memory and change the $_FILES array.
3.create a file and save the bits.
I have written a function to save file from bits,you can use it to save the upload file:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function tagsImage_upload_bits( $name, $bits){
$ifp = @ fopen( $name, ‘wb’ );
if ( ! $ifp )
{
echo “can not create file!”;
}
@fwrite( $ifp, $bits );
fclose( $ifp );
clearstatcache();// Set correct file permissions
$stat = @ stat( dirname( $name ) );
$perms = $stat[‘mode’] & 0007777;
$perms = $perms & 0000666;
@ chmod( $new_file, $perms );
clearstatcache();}
at last,i will give my plugin here and you can reference it.1
2
3
4
5
6
7
8
9
10
11
12
13
$tag=get_term_by( ‘name’, $_REQUEST[‘tagName’], ‘post_tag’ ); //用 get_term_by函数获取别名对应的标签数组
if ($tag) {$fileSave=dirname(__FILE__).’/tagimages/’.$tag->term_id.’.jpg’;
tagsImage_upload_bits($fileSave,file_get_contents($_FILES[“uploadFile”][“tmp_name”]));}
else
{
echo ‘the tag you enter does not exist!’;}
from:https://www.chaochaoblog.com/archives/632
- The topic ‘the method to upload file in wordpress plugin developing’ is closed to new replies.