# 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.

- Type: PHP
- Runs: Frontend only
- Category: [SEO](https://wpide.com/library/category/seo/)
- Tags: schema, video, youtube
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/seo-video-schema-youtube/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "VideoObject Structured Data for YouTube Embeds" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
