This tutorial will show you how to make your featured images use YouTube videos.
To achieve this, you need to overwrite the tri_post_thumbnail() function and add a custom field for the YouTube video ID.
Step 1. Create Advanced Custom Field for YouTube thumbnail
We will be using the Advanced Custom Fields plugin to create the metabox on the post edit screen. This metabox is where you will paste your YouTube video to display instead of the thumbnail image.
Install the plugin and create a new metabox. Add a Text field with the following options:
- Field Label: Youtube Video ID
- Field Name:
- Instructions: Copy the YouTube video id and paste it here. The YouTube video ID is the numbers and letters at the end of the URL. e.g. https://www.youtube.com/watch?v=0mdLV_FTqkA (the ID in this video is 0mdLV_FTqkA)
- Placeholder: 0mdLV_FTqkA
If this is intended for any other post type than your posts then change that field in the location rules section. We will also be positioning this on the side in the position field.
Once complete, Click the publish button to save the metabox.
Your fields should look similar to this
Step 2. Copy the function to child theme
Copy the tri_post_thumbnail() function located in
[code type=”markup”]tri/inc/template-tags.php[/code]
into your Tri child themes function.php file.
If you want the videos to display on both the blog index and the single blog post then you need to add the function into both the if( is_singular() ) and else php statement. Alternatively you can just put it in one or the other.
The tri_post_thumbnail() function should look similar to this:
Step 3. Add video thumbnail code to function
The code you want to display the youtube video is:
[code type=”php”]
[/code]
You can wrap that in an if else statement with the thumbnails to prevent them loading if there is a video set. If there is not a video set, you still want there to be a fallback to the image displaying.
So to do that for both blog index and blog single you would do something like this
The completed code in child functions.php
Note: the first if statement has been update to return false only if there is no featured image or youtube video too. This is reflected in the completed code above.
[code type=”php”]( ! has_post_thumbnail() && ! get_field(‘youtube_video_id’) )[/code]