How to Dynamically Change the oEmbed Width and Height in WordPress

124

In our earlier article, we showed you how to set oEmbed max width in WordPress 3.5 using $content_width. That is a perfectly good solution for changing the oEmbed max width and height, but that change is global. In a recent project, we wanted to have different oEmbed sizes for the homepage and the single post page. In this article, we will show you how to dynamically change the oEmbed max width and height in WordPress using the conditional statements.

All you have to do is add the following function in your theme’s functions.php file or in a site-specific plugin.

  //Custom oEmbed Size  function wpb_oembed_defaults($embed_size) {  if(is_front_page()) {          $embed_size['width'] = 940;          $embed_size['height'] = 600;  }  else {  	$embed_size['width'] = 600;          $embed_size['height'] = 338;  }      return $embed_size;  }  add_filter('embed_defaults', 'wpb_oembed_defaults');  

You can use any of the available WordPress conditional tags. You can even have the oEmbed width be custom for each page if need be using custom fields. Hopefully you will find this article useful in your next project.