Using WordPress ’embed_defaults’ PHP filter

The embed_defaults WordPress PHP filter allows you to customize the default dimensions of embedded content in your WordPress theme.

Usage

add_filter('embed_defaults', 'your_custom_function', 10, 2);

function your_custom_function($size, $url) {
    // your custom code here
    return $size;
}

Parameters

  • $size (int[]): Indexed array of the embed width and height in pixels.
  • $size[0] (int): The embed width.
  • $size[1] (int): The embed height.
  • $url (string): The URL that should be embedded.

More information

See WordPress Developer Resources: embed_defaults

Examples

Change default embed size

Customize the default width and height of embedded content:

add_filter('embed_defaults', 'change_default_embed_size', 10, 2);

function change_default_embed_size($size, $url) {
    $size[0] = 600; // Set width to 600 pixels
    $size[1] = 400; // Set height to 400 pixels

    return $size;
}

Set embed size based on content width

Set the embed size according to the theme’s content width:

add_filter('embed_defaults', 'set_embed_size_based_on_content_width', 10, 2);

function set_embed_size_based_on_content_width($size, $url) {
    $content_width = isset($GLOBALS['content_width']) ? $GLOBALS['content_width'] : 500;
    $size[0] = $content_width;
    $size[1] = round($content_width * 1.5);

    return $size;
}

Different embed size for specific URLs

Set a different embed size for a specific URL:

add_filter('embed_defaults', 'specific_url_embed_size', 10, 2);

function specific_url_embed_size($size, $url) {
    if ($url === 'https://example.com/special-video/') {
        $size[0] = 800; // Set width to 800 pixels
        $size[1] = 450; // Set height to 450 pixels
    }

    return $size;
}

Set embed size for specific post types

Change the embed size based on the current post type:

add_filter('embed_defaults', 'set_embed_size_for_post_type', 10, 2);

function set_embed_size_for_post_type($size, $url) {
    global $post;

    if ($post->post_type === 'custom_post_type') {
        $size[0] = 700; // Set width to 700 pixels
        $size[1] = 393; // Set height to 393 pixels
    }

    return $size;
}

Set maximum embed size

Limit the maximum width and height of embedded content:

add_filter('embed_defaults', 'limit_max_embed_size', 10, 2);

function limit_max_embed_size($size, $url) {
    $max_width = 800;
    $max_height = 450;

    if ($size[0] > $max_width) {
        $size[0] = $max_width;
    }

    if ($size[1] > $max_height) {
        $size[1] = $max_height;
    }

    return $size;
}