phpwordpressid3v2

How to automatically create wordpress posts for each mp3 uploaded?


I have a wordpress site, and its about media sharing. I have uploaded mp3 files as albums and created a post for each album. But I want to create individual post for each mp3 files uploaded automatically.

I have already tried mp3-to-post plugin, but that's not supported for the latest version of wordpress and I have tried uploading the plugin, and it doesn't work.


Solution

  • Using do_action( 'add_attachment', $post_ID ) hook you can create respective post. For ref - see wp_insert_post function

    To do the above, add follows code snippet in your active theme's functions.php -

    function action_add_attachment( $post_ID ) { 
        if( !$post_ID ) return;
        $attachment = get_post( $post_ID );
        // Create album post object for attachment post ID
        $attachment_post = array(
          'post_title'    => 'Album - ' . $attachment->post_title,
          'post_content'  => 'Your post content goes here',
          'post_status'   => 'publish',
          'post_author'   => $attachment->post_author
        );
    
        // Insert the post 
        wp_insert_post( $attachment_post );
    }
    
    add_action( 'add_attachment', 'action_add_attachment', 99 );