Assuming that you have a Custom Post Type “myaudio”:
Create a function to render the upload page
<?php
function brg_upload_audio_page(){
//display uplaod form
if (empty($_POST)){ ?>
<h2>Upload Audio</h2>
<form action="" method="post" enctype="multipart/form-data">
<p>Title of the song</p>
<input type="text" name="post_title">
<p>File</p>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload" name="submit">
</form>
<?php }
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
if (!empty($_POST)){
$uploadedfile = $_FILES['fileToUpload'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
$title = $_POST['post_title'];
if ( $movefile ) {
$uploaded_file = $movefile["file"];
//create a post with the custom post type my_audio
$post_args = array (
'post_status' => 'publish',
'post_type' => 'myaudio',
'post_title' => $title,
'post_content' => '',
$parent_post_id = wp_insert_post( $post_args );
$filetype = wp_check_filetype( basename( $uploaded_file), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . "https://wordpress.stackexchange.com/" . basename( $uploaded_file ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $uploaded_file ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment to the post
$attach_id = wp_insert_attachment( $attachment, $uploaded_file, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
} else {
echo "File upload failed";
}
}
}
//create the menu item and the page for upload
function register_brg_upload_menu() {
add_menu_page( 'My Audio', 'My Audio', 'manage_options', 'brg_upload_audio_page', 'brg_upload_audio_page', 'dashicons-portfolio', 1.1);
$submenu_pages = array(
// Avoid duplicate pages. Add submenu page with same slug as parent slug.
array(
'parent_slug' => 'brg_upload_audio_page',
'page_title' => 'Upload',
'menu_title' => 'Upload',
'capability' => 'manage_options',
'menu_slug' => 'brg_upload_audio_page',
'function' => 'brg_upload_audio_page',// Uses the same callback function as parent menu.
)
);
// Add each submenu item to custom admin menu.
foreach($submenu_pages as $submenu){
add_submenu_page(
$submenu['parent_slug'],
$submenu['page_title'],
$submenu['menu_title'],
$submenu['capability'],
$submenu['menu_slug'],
$submenu['function']
);
}
}
add_action( 'admin_menu', 'register_brg_upload_menu' );