Wordpress自定义插件上传图片

时间:2014-04-28 18:36:42

标签: php wordpress wordpress-theming

我正在编写一个自定义wordpress插件,让用户将图像上传到文件夹。 而我在将实际图像保存到文件夹时遇到问题。

这是我的myplugin.php

add_action( 'admin_menu', 'register_my_custom_menu_page' );

function register_my_custom_menu_page(){
    add_menu_page( 'Home Page', 'Home Page', 'manage_options', 'homepage', 'my_custom_menu_page', plugins_url( 'myplugin/images/icon.png' ), 6 ); 
}

function my_custom_menu_page(){
    echo '<h1>Settings</h1>';
    echo '<form method="post" action="process.php" enctype="multipart/form-data">';
    echo '<table>';

    echo '<tr><td>Image 1</td><td><input type="file" name="file1" size="40"></td></tr>';    
    echo '<tr><td></td><td><input type="submit" name="submit" value="Update" /></td></tr>';     
    echo '</table>';
    echo '</form>';
 }

这是我的process.php,我在wp上传文件夹中看不到图像。请帮忙!

move_uploaded_file($_FILES["cul_center"]["tmp_name"], wp_upload_dir().$_FILES["file1"]["name"]);

1 个答案:

答案 0 :(得分:0)

您不需要为此使用PHP本机函数。

Wordpress提供wp_handle_upload()功能来处理上传并明确移动/uploads/year/month/

用法(在您的情况下):

require_once( ABSPATH . 'wp-admin/includes/file.php' ); // require file.php

$uploadedfile = $_FILES['file1']; // your file input

$upload_overrides = array( 'test_form' => false ); // you need to do this according to docs

$movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); //let it handle uploads

if ( $movefile ) {
    echo "File is valid, and was successfully uploaded.\n";
    var_dump( $movefile); // will print associative array of file attributes.
}