Skip to main content

Automatic chapter links

I love the timestamp links, but hate to add every link by hand. I've created a snippet that automatically creates a timestamp link list for all available chapters

/**

  • FluentPlayer β€” Auto Chapter Links
  • Genereert automatisch [fluentplayer_timestamp] links uit de chapters van een media.
  • Gebruik: [fluentplayer_auto_chapters id="129"]
    */
    defined( 'ABSPATH' ) || exit;

add_action( 'init', function () {
if ( ! class_exists( '\FluentPlayer\App\Models\Media' ) ) {
return;
}

add_shortcode( 'fluentplayer_auto_chapters', function ( $atts ) {
    $atts = shortcode_atts( [
        'id'       => '',
        'media_id' => '',
    ], $atts );

    $mediaId = absint( $atts['id'] ?: $atts['media_id'] );
    if ( ! $mediaId ) {
        return '';
    }

    $media = \FluentPlayer\App\Models\Media::findVisible( $mediaId );
    if ( ! $media ) {
        return '';
    }

    $chapters = (array) ( $media->settings['chapters'] ?? [] );
    if ( empty( $chapters ) ) {
        return '';
    }

    usort( $chapters, fn( $a, $b ) => ( $a['startTime'] ?? 0 ) <=> ( $b['startTime'] ?? 0 ) );

    $items = '';
    foreach ( $chapters as $chapter ) {
        $title = trim( (string) ( $chapter['title'] ?? '' ) );
        if ( $title === '' ) {
            continue;
        }
        $timeLabel = fp_auto_chapters_format_time( (float) ( $chapter['startTime'] ?? 0 ) );
        $items    .= sprintf(
            '<li class="fp-auto-chapter-item"><fluentplayer-timestamp time=\'%s\' media_id=\'%d\'>%s</fluentplayer-timestamp></li>',
            esc_attr( $timeLabel ),
            $mediaId,
            wp_kses_post( $title )
        );
    }

    return $items ? '<ul class="fp-auto-chapters-list">' . $items . '</ul>' : '';
} );

} );

if ( ! function_exists( 'fp_auto_chapters_format_time' ) ) {
function fp_auto_chapters_format_time( $seconds ) {
$seconds = max( 0, (int) round( $seconds ) );
$h = (int) floor( $seconds / 3600 );
$m = (int) floor( ( $seconds % 3600 ) / 60 );
$s = $seconds % 60;
return $h > 0 ? sprintf( '%d:%02d:%02d', $h, $m, $s ) : sprintf( '%d:%02d', $m, $s );
}
}

Great, thanks 😎