1

The issue I am trying to solve is within the WordPress loop, I only want video embeds or images to display, not any text.

Currently, when creating a new post (Standard format) in the WordPress editor, most of my posts look like this:

http://youtube.com/somevideo

Some supporting text below the video

And of course WordPress will then create an automatically embedded video using whatever YouTube or Vimeo link I put in there.

When displaying the list of posts, I do not want Some supporting text below the video to display, only the video.

Currently my content.php page is pretty basic and just displays the content using <?php the_content(); ?>

Is there a way to strip out this text on each post?

1

We can do that with the help of the get_media_embedded_in_content() function:

/**
 * Display only the first media item in the content
 *
 * @link http://wordpress.stackexchange.com/a/199398/26350
 */
! is_admin() && add_filter( 'the_content', function( $content )
{
    // Get the avialable media items from the content
    add_filter( 'media_embedded_in_content_allowed_types', 'wpse_media_types' );
    $media = get_media_embedded_in_content( $content );
    remove_filter( 'media_embedded_in_content_allowed_types', 'wpse_media_types' );

    // Only use the first media item if available 
    if( $media ) 
        $content = array_shift( $media );   

    return $content;
} , 99 );

where we can define our custom media types with:

function wpse_media_types( $types )
{
   return [ 'audio', 'video', 'object', 'embed', 'iframe', 'img' ];
}

Here's another approach where we extract all the urls from the content and check if it's an available oEmbed:

/**
 * Display only the first oEmbed in the content
 *
 * @link http://wordpress.stackexchange.com/a/199398/26350
 */
! is_admin() && add_filter( 'the_content', function( $content )
{
    require_once( ABSPATH . WPINC . '/class-oembed.php' );
    $wp_oembed = _wp_oembed_get_object();
    $urls = wp_extract_urls( $content );
    foreach( (array) $urls as $url )
    {
        if( $wp_oembed->get_provider( $url ) )
            $content = $url;
    }
    return $content;
}, 1 );

Note that you might want to add further restriction on where you want to use this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.