These two functions here will grab data from the YouTube API about a video:
// function to parse the code from the URL
function parse_youtube_video_id_from_url( $video_url ) {
$splited_data = explode( '=', $video_url );
$video_unique_code = substr( $splited_data[1], 0, -strlen( strrchr( $splited_data[1], '&' ) ) );
return $video_unique_code;
}
// use the youtube APIs to get a json string containing data about the video
function get_youtube_json_video_data( $video_code ) {
$api_url = "https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&q={$video_code}";
$data = wp_remote_get( $api_url );
return wp_remote_retrieve_body( $data );
}
You must use these to get the time data
So for your example, here’s how you’d get the data:
$youtubecode="QiNIfGiNiOk"; // replace with your youtube code or variable etc etc..
$video_data = get_youtube_json_video_data($youtubecode);
$video_data = json_decode( $video_data );
Then finally, to see what data you got, let’s pass the video_data
into print_r
to put some debug output on the screen:
// lets print out the data so we can see what we got:
printf( '<pre>%s</pre>', var_export( $video_data, true ) );
You should see a pre
tag containing a PHP data structure with everything you could ever want to know about the YouTube video (assuming the video exists).
And there you go, $video_data
should contain the time, description, uploader, all the thumbnails, ratings, etc
You would then use this new found knowledge to create a function, hook that function into the 'save_post'
and 'publish_post'
actions, that updates the post meta/custom field based on the above code
How to use filters and actions, or how to grab from or save to a custom field, is beyond the scope of your question.