Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.