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.
wp_upload_bits()
)$_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 :)
You are missing some lines of code for the $_FILES
to get populated.
add_action( 'post_edit_form_tag', 'update_edit_form' );
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
Worked for me locally.
https://tommcfarlin.com/upload-files-in-wordpress/ (down in the comments)