Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- *
- * Filter subtitles
- *
- * @param array $tracks
- * @param int $post_id
- *
- */
- add_filter( 'streamtube/core/post/text_tracks', function( $tracks, $post_id ){
- // Return tracks if they have been manually uploaded through the form.
- // Otherwise, remove these two lines.
- if( $tracks ){
- return $tracks;
- }
- $_tracks = array();
- // Get the video URL meta value
- $video_url = get_post_meta( $post_id, 'video_url', true );
- if( ! $video_url ){
- return false;
- }
- // Extract the YouTube ID from the video URL
- preg_match('/(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $video_url, $matches);
- if( ! $matches || ! isset( $matches[1] ) ){
- return false;
- }
- $youtube_id = $matches[1];
- // Directory where subtitle files are stored
- $subtitle_dir = WP_CONTENT_DIR . '/uploads/subtitles/' . $youtube_id;
- // Check if directory exists
- $subtitle_files = array();
- if( is_dir( $subtitle_dir ) ){
- // Scan the directory for .vtt files
- $subtitle_files = glob( $subtitle_dir . '/*.vtt' );
- }
- // Get the text tracks from post meta
- $tracks = get_post_meta( $post_id, 'text_tracks', true );
- if( $tracks && is_array( $tracks ) && array_key_exists( 'languages', $tracks ) && is_array( $tracks['languages'] ) ){
- for ( $i = 0; $i < count( $tracks['languages'] ); $i++) {
- if( $tracks['languages'][$i] && $tracks['sources'][$i] ){
- $file_type = wp_check_filetype( $tracks['sources'][$i] );
- if( array_key_exists( 'ext', $file_type ) && in_array( strtolower( $file_type['ext'] ), apply_filters( 'streamtube/core/text_track_format', array( 'vtt' ) ) ) ){
- $_tracks[] = array(
- 'language' => $tracks['languages'][$i],
- 'source' => $tracks['sources'][$i]
- );
- }
- }
- }
- }
- // Add local subtitle files if not already added
- if( $subtitle_files ){
- foreach ( $subtitle_files as $subtitle_file ) {
- $file_name = basename( $subtitle_file, '.vtt' );
- $file_parts = explode('.', $file_name);
- if( count( $file_parts ) >= 2 && $file_parts[0] === $youtube_id ){
- // Extract language code before the hyphen if present
- $language = explode('-', $file_parts[1])[0];
- $source = content_url( '/uploads/subtitles/' . $youtube_id . '/' . basename( $subtitle_file ) );
- // Check if this language is already added from meta
- $language_exists = false;
- foreach( $_tracks as $track ){
- if( $track['language'] === $language ){
- $language_exists = true;
- break;
- }
- }
- if( ! $language_exists ){
- $_tracks[] = array(
- 'language' => $language,
- 'source' => $source
- );
- }
- }
- }
- }
- return $_tracks;
- }, 10, 2 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement