VideoObject Structured Data for YouTube Embeds
Finds YouTube videos embedded in a post and adds VideoObject JSON-LD for each, with thumbnail and embed URL, so the page can show video results in search.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
if ( ! is_singular() ) {
return;
}
$post = get_queried_object();
if ( ! $post instanceof WP_Post || false === stripos( $post->post_content, 'youtu' ) ) {
return;
}
preg_match_all( '#(?:youtube(?:-nocookie)?\.com/(?:watch\?(?:.*&)?v=|embed/|shorts/)|youtu\.be/)([A-Za-z0-9_-]{11})#', $post->post_content, $matches );
$ids = array_slice( array_unique( $matches[1] ), 0, 3 );
if ( ! $ids ) {
return;
}
$graph = array();
foreach ( $ids as $i => $id ) {
$graph[] = array(
'@type' => 'VideoObject',
'name' => wp_strip_all_tags( get_the_title( $post ) ) . ( $i ? ' (' . ( $i + 1 ) . ')' : '' ),
'description' => wp_strip_all_tags( get_the_excerpt( $post ) ) ?: wp_strip_all_tags( get_the_title( $post ) ),
'thumbnailUrl' => 'https://i.ytimg.com/vi/' . $id . '/hqdefault.jpg',
'uploadDate' => get_the_date( DATE_W3C, $post ),
'embedUrl' => 'https://www.youtube.com/embed/' . $id,
);
}
echo '<script type="application/ld+json">' . wp_json_encode( array( '@context' => 'https://schema.org', '@graph' => $graph ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) . "</script>\n";
} );
Notes
Uses the post title, excerpt and publish date for every video (up to three per page); no requests are sent to YouTube.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.