How to Replace the WordPress Featured Image with a Video?

I need to replace featured images on pages with a video if certain posts contain a video from YouTube, Vimeo, other video hosting services allowed by WordPress.

Here’s the pseudo code that I want to use on a custom page:

if ( has_post_thumbnail( get_the_ID() {
    if has_video(pseudocode to check whether the single post contains youtube video)  {
// show video player
    } else {
// show post thumbnail
    }
}

Any tips?

2 Answers
2

Let’s say for simplicity that you’re using ACF. You need to create a video link field once ACF is installed and assign it to posts. Then, in the post you want a video to show up, add the url. I usually assign this field as a text field and then have users enter the youtube id (last string of text after the youtube.com link.

For example, if the video link was: https://www.youtube.com/J-ek8drxFJA

the user would enter just J-ek8drxFJA in the field.

Now add this code to your single.php copy that is in your child theme folder

Notice that I changed the if statement. No need to look for the thumbnail if you’re going to use a video:

if( get_field( 'video_link' ) ) {
    echo 'this is my video link id ' . get_field( 'video_link' );   // or show video player (see below)
} else {
    if( has_post_thumbnail( get_the_ID() {
        // show post thumbnail
    }

    //no video or photo
}

Now of course if you want to show the video you’ll want to do something like this instead:

if( get_field( 'video_link' ) ) {
    $videoid = get_field( 'video_link' );
    echo '<h2>Video Link</h2><p>see our video:</p><iframe width="420" height="315" src="https://www.youtube.com/embed/' . $videoid . '" frameborder="0" allowfullscreen></iframe>';
} else {
    if( has_post_thumbnail( get_the_ID() ) ) {
        // show post thumbnail
    }

    //no video or photo
}

Obviously you can change the code up a bit to suit your needs.

Leave a Comment