Using WordPress ‘get_media_item()’ PHP function

The get_media_item() WordPress PHP function retrieves the HTML form for modifying an image attachment.

Usage

get_media_item( $attachment_id, $args );

Example:

Input:

get_media_item( 42, array( 'toggle' => false ) );

Parameters

  • $attachment_id (int) – Required. The ID of the attachment for modification.
  • $args (string|array) – Optional. Used to override the default arguments. Default: null.

More information

See WordPress Developer Resources: get_media_item()

Examples

Displaying the edit form for an image attachment

This code displays the edit form for an image attachment with ID 42.

$attachment_id = 42;
echo get_media_item( $attachment_id );

Customizing the edit form with arguments

This code displays the edit form for an image attachment with ID 42 and disables the toggle button.

$attachment_id = 42;
$args = array( 'toggle' => false );
echo get_media_item( $attachment_id, $args );

Displaying the edit form for multiple image attachments

This code displays the edit form for multiple image attachments with their respective IDs.

$attachment_ids = array( 42, 43, 44 );
foreach ( $attachment_ids as $attachment_id ) {
    echo get_media_item( $attachment_id );
}

Customizing the edit form for multiple image attachments

This code customizes and displays the edit form for multiple image attachments by disabling the toggle button.

$attachment_ids = array( 42, 43, 44 );
$args = array( 'toggle' => false );

foreach ( $attachment_ids as $attachment_id ) {
    echo get_media_item( $attachment_id, $args );
}

Using get_media_item() with custom post types

This code displays the edit form for an image attachment associated with a custom post type named product.

$args = array(
    'post_type'   => 'product',
    'numberposts' => 1,
    'post_status' => 'any',
);

$products = get_posts( $args );
if ( $products ) {
    $product = $products[0];
    $attachment_id = get_post_thumbnail_id( $product->ID );
    echo get_media_item( $attachment_id );
}