Using WordPress ‘get_post_embed_html()’ PHP function

The get_post_embed_html() WordPress PHP function retrieves the embed code for a specific post.

Usage

get_post_embed_html( $width, $height, $post = null );

Parameters

  • $width (int) – The width for the response.
  • $height (int) – The height for the response.
  • $post (int|WP_Post) – Optional. Post ID or object. Default is global $post. Default value: null.

More information

See WordPress Developer Resources: get_post_embed_html()

Examples

Get embed code for the current post

This example retrieves the embed code for the current post with a width of 600 and a height of 400.

// Get the embed code for the current post
$embed_code = get_post_embed_html( 600, 400 );
echo $embed_code;

Get embed code for a specific post by ID

This example retrieves the embed code for a post with an ID of 45, width of 800, and height of 450.

// Get the embed code for the post with ID 45
$embed_code = get_post_embed_html( 800, 450, 45 );
echo $embed_code;

Get embed code for a specific post using a WP_Post object

This example retrieves the embed code for a post using a WP_Post object, width of 640, and height of 360.

// Get a WP_Post object for a post with ID 120
$my_post = get_post( 120 );

// Get the embed code for the post using the WP_Post object
$embed_code = get_post_embed_html( 640, 360, $my_post );
echo $embed_code;

Get embed code with custom width and height using post meta

This example retrieves the embed code for the current post, with width and height values stored as post meta.

// Get custom width and height from post meta
$custom_width = get_post_meta( get_the_ID(), 'custom_width', true );
$custom_height = get_post_meta( get_the_ID(), 'custom_height', true );

// Get the embed code for the current post with custom width and height
$embed_code = get_post_embed_html( $custom_width, $custom_height );
echo $embed_code;

Display embed code for all posts in a loop

This example displays the embed code for each post in a loop, with a width of 500 and a height of 300.

// The WordPress loop
if ( have_posts() ) {
  while ( have_posts() ) {
    the_post();

    // Get the embed code for the current post
    $embed_code = get_post_embed_html( 500, 300 );
    echo $embed_code;
  }
}