Pull YouTube Description into WordPress Content

Published: 11, Dec 2014
DevelopmentPHPWordPress

You might find yourself needing to dynamically update your WordPress post content with the description of a YouTube video.

I put together the following function to accomplish just that!

function update_description_with_youtube( $post_id ) {

	if ( ! wp_is_post_revision( $post_id ) ){
		
		// unhook this function so it doesn't loop infinitely
		remove_action('save_post', 'update_description_with_youtube');

		$youtubeURL =   get_field('youtube_id',$post_id);

		if (FALSE === strpos($youtubeURL, 'youtu.be')) {
		    parse_str(parse_url($youtubeURL, PHP_URL_QUERY), $youtube_ID);
		    $youtube_ID = $youtube_ID['v'];
		} else {
		    $youtube_ID = basename($youtubeURL);
		}

		$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$youtube_ID.'?v=2&alt=json&prettyprint=true';		
		$response = json_decode(file_get_contents($feedURL), true);
		

		$description    =   esc_attr($response['entry']['media$group']['media$description']['$t']);

		// Update post
		  $exercise = array(
		      'ID'           => $post_id,
		      'post_content' => $description
		  );

		// Update the post into the database
		  wp_update_post( $exercise );

		  return;

	  	// re-hook this function
	  	add_action('save_post', 'update_description_with_youtube');
	  }
}
add_action( 'save_post', 'update_description_with_youtube' );

This can be a bit tricky due to the fact you’re using the save_post hook from WordPress, while also using the wp_update_post function together which, if not done right can cause an infinite loop.

We can take care of this by unhooking our function, within the save_post call, running our custom function, and then re-initializing our hook.

We get our YouTube Video ID by parsing an ACF (Advanced Custom Fields) field that can either handle a single Youtube ID, or even a complete youtube URL.  This function parses any youtube URL, and then returns the ID of that actual youtube video, then passes it to our description pulling function.