Hide YouTube related videos from other channels using WordPress Embed

When you add YouTube videos on your WordPress website using default WordPress Embed or the YouTube block, from block editor (which eventually uses WP Embed), it shows a nice YouTube video. But at the end of the video, you will see some “related videos”, which are from different channels. This is a deal breaker for many. Specially for those who created those videos for the purpose of showing them on their website.

Previously, there were option to turn off related videos entirely. But YouTube has removed this option. We can use rel=0 parameter with embed code to only show related videos from the same channel. So, adding rel=0 will stop showing related videos from other channels.

Following code updates WordPress Embed code to add rel=0 with every YouTube embed, whether it’s from classic or block editor.

function careless_youtube_oembed_related_videos( $html, $url, $args ) {
    //we will only update youtube videos
    if ( strpos( $html, 'youtube' ) !== false ) {
        $html = str_replace( 'feature=oembed', 'feature=oembed&rel=0', $html );
    }

    return $html;
}
add_filter( 'oembed_result', 'careless_youtube_oembed_related_videos', 9999, 3 );

Code goes in the functions.php file of your active theme.