search ]

Check if a Post Has Embedded Content

The following snippet lets you check whether a specific post has embedded content. It works inside the loop using the post ID. Alternatively, you can pass any ID to check if that post contains embedded content.

<?php

function has_embed( $post_id = false ) {
	if( !$post_id ) $post_id = get_the_ID();
	else $post_id = absint( $post_id );
	if( !$post_id ) return false;

	$post_meta = get_post_custom_keys( $post_id );
	$post_meta = array_map( 'trim' , $post_meta );

	foreach( $post_meta as $meta ) {
		if( '_oembed' != substr( $meta , 0 , 7 ) )
			continue;
		return true;
	}
	return false;
}

Usage:

if( has_embed() ) {
   // do whatever
}

For more on embedded content, see Improving Loading Time of Embedded Videos.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo