WordPress: Custom has_embed function

Taken from the great t31os!

Recently someone on the WordPress forums asked if there was an easy way to determine if a post has any content embedded and if so, a link could be provided to indicate the visitor should click it to see the full post where the embedded content is available.

The well known function the_excerpt() does not show embedded content, so an archive listing displaying excerpts would have no ordinary way to indicate content such as a Youtube video is available inside the full posting.

I wrote this very simple function for checking if a post(or page presumably) has any content embedded inside.

 

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 );

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

The function is not designed to output any link, or data, it’s simpy a true or false return statement so you can determine if a given post(or page) has embedded content, what you place inside the conditional check is up to you, but here’s a very basic example that i provided along with the function initially.

<?php if( has_embed() ) : ?>
    <a href="<?php the_permalink(); ?>" title="Click to see the Video">Click here to see the Video</a>
<?php endif; ?>

What goes inside that condition is entirely down to you and what you want to have there, the example is simply for illustration of how to use the function.

Code works under the current release 2.9.2 and also has been tested under WordPress 3.0 Beta2.

If you find the function useful please feel free to share a comment or rate the post, no registration is required but i do moderate your first couple of comments (can you blame me with all the spam around?).

Revisions

Tags: ,

No comments yet.

Leave a Reply