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条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改