Halloween Sale 15% off Ends in See the plans
PHP

Remind Editors to Add Captions to Videos

Shows a warning after saving when a post contains a Video block without a captions or subtitles track, so videos are not published without captions by accident.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'save_post', function ( $post_id, $post ) {
    if ( wp_is_post_revision( $post_id ) || ! has_block( 'core/video', $post ) || ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    $missing = 0;

    foreach ( parse_blocks( $post->post_content ) as $block ) {
        if ( 'core/video' === $block['blockName'] && empty( $block['attrs']['tracks'] ) ) {
            $missing++;
        }
    }

    if ( $missing ) {
        set_transient( 'wpide_caption_notice_' . get_current_user_id(), $missing, MINUTE_IN_SECONDS );
    }
}, 20, 2 );

add_action( 'admin_notices', function () {
    $key     = 'wpide_caption_notice_' . get_current_user_id();
    $missing = (int) get_transient( $key );

    if ( ! $missing ) {
        return;
    }

    delete_transient( $key );
    printf( '<div class="notice notice-warning is-dismissible"><p>%s</p></div>', esc_html( sprintf( '%d video(s) in this post have no captions track. Add one in the Video block settings under "Text tracks".', $missing ) ) );
} );

Notes

Add captions in the Video block settings under "Text tracks"; embedded YouTube and Vimeo videos manage captions on their own platform.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.