WordPress allows users to easily embed video links directly onto a post in 2 ways:
- Using Video Shortcode
- Just paste plain video links if you are enabling Jetpack plugin
But what happens if you are collecting a video link from a custom field and then trying to show the video on a post?
Don’t worry, this can be done via the wp_oembed_get()
function. (Codex: wp_oembed_get)
Snippet:
Here’s the full function we’ll be using for this purpose. Just put it in your functions.php
.
/* * Embed video with URL retrieved from custom fields * URL: http://clonetemplates.com/codex/embed-video-url-retrieved-custom-fields.html/ */ function ct_video_url_custom_field($field) { global $post; if(empty($field)) $field='_ct_video_url'; $supported = wp_get_video_extensions(); $video_url = get_post_meta($post->ID, $field, true); $video_pathinfo = pathinfo($video_url); $video_ext = $video_pathinfo['extension']; if ( in_array($video_ext, $supported) ) { wp_video_shortcode(array('src'=>$video_url)); } else { $video = wp_oembed_get($video_url); echo $video; } }
Line 5: To get the url from custom field, we’ll use the get_post_meta()
function. $field
is the key of the custom field.
So if the $video_url
has one of the standard extensions that is supported by wp, it will do the video src shortcode. If not, it will try to oembed the url.
Usage:
Put following code to where you want to show the video. This functions must be used in the loop.
<?php ct_video_url_custom_field('field_key');?>
Remember to replace field_key
with your actual custom field key
References:
- http://wordpress.org/support/topic/how-to-embed-audio-video-with-url-retrieved-from-custom-fields
- http://www.limecanvas.com/passing-parameters-to-a-video-link-in-a-wordpress-custom-field/
Leave A Comment