dongming4994 2017-09-25 15:59
浏览 67
已采纳

$ _FILES在WordPress上传元上传框中一直为空

I'm feeling silly. I'm building my first WordPress plugin. The first goal is to add a custom meta box to a post that will allows an audio upload. I have the meta box created, and when I use a text input, the code works fine. When I try to convert the input into a file upload though, I'm running into a problem.

  1. The file never uploads (I'm using wp_upload_bits())
  2. $_FILES seems to always be empty. In the below example, when I call something like $_FILES[ 'audio_box' ], I always get an invalid or unavailable key.

Here's a simplified version of the code I'm using. I have nonces and all that setup in the real version!

<?php

add_action( 'load-post.php', 'file_upload_setup' );
add_action( 'load-post-new.php', 'file_upload_setup' );

function file_upload_setup() {
    add_action( 'add_meta_boxes', 'file_upload_box' );
    add_action( 'save_post', 'upload_save_post_class_meta' );
}

function file_upload_box() {
    add_meta_box(
        'audio_box',    // Unique ID
        esc_html__( 'Title' ),
        'audio_box',   // Callback function
        'post',         // Admin page (or post type)
        'side',         // Context
        'default'         // Priority
    );
}

function upload_save_post_class_meta( $post_id ) {
    if ( !empty( $_FILES[ 'audio_box' ] ) ) {
        $upload = wp_upload_bits( $_FILES[ 'audio_box' ][ 'name' ],
            null,
            file_get_contents( $_FILES[ 'audio_box' ][ 'tmp_name' ] )
        ); 
    }
}

function file_upload_box( $post ) { ?>
    <p>
        <label for="file_upload_box"><?php _e( "Upload an audio file to accompany your post." ); ?></label>
        <br />
        <input
            class="widefat"
            type="file"
            name="audio_box" 
            id="audio_box" 
            value="<?php 
                    echo esc_attr(
                        get_post_meta( $post->ID, 'audio_box', true ) 
                    );
                ?>" 
            size="30" 
        />
    </p>
<?php }

?>

Is there anything special I need to do here to get the file to upload to the media library on save?

Thanks all! Long time listener, first time caller :)

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流