How can I display YouTube videos instead of thumbnails?

Embed YouTube video in the front page or category pages in WordPress
Figure 1: YouTube video in the front page or category pages in WordPress

I wanted a WordPress theme which displays YouTube videos instead of thumbnails in a front page or category pages like the screenshot above. I found some paid themes provide such a feature but I could not find the one which meets my requirements. So I decided to change thumbnails in the excerpts with YouTube videos for myself.

It's very easy and straightforward to implement it. There may be several ways to do it. I chose to use custom fields. First, I installed the "Custom Post Type UI" plugin. I, then, created a field named YouTube, which will be embedded in an excerpt.

Create a custom field using ACF

As shown above, please create a custom field. Now, you will see this custom filed shown in a "Edit Post" screen.

Embed YouTube URL in a custom field

You can enter a YouTube video URL or Vimeo video URL (e.g.; see this)url in the field "YouTube" above.

Now we need to make this custom field displayed in an excerpt. I want to show the YouTube video if the custom field ("YouTube") exist. If there is no custom field, the featured image (thumbnail) will be displayed if any. To display YouTube videos embedded in the custom fields, we can use the following code:

<?php if( get_field('youtubeurl') ){
$embed_code = wp_oembed_get( get_field('youtubeurl'), array('width'=>300) );
echo $embed_code;
} ?>

Please search "<?php the_excerpt(); ?>" in index.php, category.php or content.php (which may be different depending on your theme.)  You will see "the_post_thumbnail" (for example, "<?php the_post_thumbnail('excerpt-thumbnail', 'class=alignleft'); ?>"). Now you can make a conditional tag to check if the custom filed exists to display the video first, and then to check if there is a featured image. (I will skip the detailed code since it's very easy to create one.) Please refer to Figure 1 for the final result.



Leave a Comment