吵吵   2011-08-24  阅读:2,412

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:









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:

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.

$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!';

}

吵吵微信朋友圈,请付款实名加入:

吵吵 吵吵

8条回应:“the method to upload file in wordpress plugin developing”

  1. 说道:

    哇塞,你还搞起了英文翻译……

  2. 流氓兔足迹说道:

    哇,英文啊!为什么这样弄??

  3. 七七说道:

    关注,支持一个

  4. 红涛SEO博客说道:

    呵呵,全是英文啊

  5. 张海华说道:

    你么得事吧!

    全搞英文!

    好歹也要搞个翻译!

  6. 海棠果说道:

    I must learn more about wordpress plugin how to upload .

  7. 小糊涂博客说道:

    你让我情何以堪?

  8. 地球博客说道:

    英文看不懂,来支持一下。

发表评论

电子邮件地址不会被公开。 必填项已用*标注