Using WordPress ‘get_oembed_response_data_rich()’ PHP function

The get_oembed_response_data_rich() WordPress PHP function filters the oEmbed response data to return an iframe embed code.

Usage

get_oembed_response_data_rich($data, $post, $width, $height);

Parameters

  • $data (array): Required. The response data.
  • $post (WP_Post): Required. The post object.
  • $width (int): Required. The requested width.
  • $height (int): Required. The calculated height.

More information

See WordPress Developer Resources: get_oembed_response_data_rich

Examples

Basic usage of get_oembed_response_data_rich

In this example, we will use the get_oembed_response_data_rich() function to filter the oEmbed response data and return an iframe embed code for a specific post.

// Fetch post object.
$post = get_post(42);

// Define width and height.
$width = 640;
$height = 480;

// Get oEmbed response data.
$data = wp_oembed_get($post->guid);

// Get iframe embed code.
$embed_code = get_oembed_response_data_rich($data, $post, $width, $height);

// Display the embed code.
echo $embed_code;

Customize the oEmbed response data

In this example, we will modify the oEmbed response data by adding a custom CSS class to the iframe.

// Add a custom CSS class to the oEmbed response data.
function add_custom_class_to_oembed($data, $post, $width, $height) {
    $data['html'] = str_replace('class="', 'class="custom-class ', $data['html']);
    return $data;
}
add_filter('get_oembed_response_data_rich', 'add_custom_class_to_oembed', 10, 4);

Adjust the oEmbed aspect ratio

In this example, we will adjust the aspect ratio of the oEmbed iframe to 16:9.

// Adjust the aspect ratio of the oEmbed iframe.
function adjust_oembed_aspect_ratio($data, $post, $width, $height) {
    $height = intval($width * (9 / 16));
    $data['height'] = $height;
    $data['html'] = preg_replace('/height="\d+"/', 'height="' . $height . '"', $data['html']);
    return $data;
}
add_filter('get_oembed_response_data_rich', 'adjust_oembed_aspect_ratio', 10, 4);

Set a maximum oEmbed iframe width

In this example, we will limit the width of the oEmbed iframe to a maximum of 800 pixels.

// Set a maximum width for the oEmbed iframe.
function set_max_oembed_width($data, $post, $width, $height) {
    $max_width = 800;
    if ($width > $max_width) {
        $data['width'] = $max_width;
        $data['html'] = preg_replace('/width="\d+"/', 'width="' . $max_width . '"', $data['html']);
    }
    return $data;
}
add_filter('get_oembed_response_data_rich', 'set_max_oembed_width', 10, 4);