Using WordPress ‘get_media_items()’ PHP function

The get_media_items() WordPress PHP function retrieves the HTML for media items of a post gallery.

Usage

get_media_items($post_id, $errors);

Custom Example:

Input:

$post_id = 123;
$errors = array();
echo get_media_items($post_id, $errors);

Output:

HTML markup for media items of the post gallery with ID 123.

Parameters

  • $post_id (int): The ID of the post for which you want to retrieve the media items.
  • $errors (array): An array of errors related to the attachment, if any.

More information

See WordPress Developer Resources: get_media_items

Examples

Display media items of a specific post

In this example, we retrieve the media items of a post with ID 123 and display the generated HTML.

$post_id = 123;
$errors = array();
echo get_media_items($post_id, $errors);

Display media items with error messages

In this example, we display media items of a post with ID 123 along with any error messages associated with the attachments.

$post_id = 123;
$errors = array("Image 1" => "Error message 1", "Image 2" => "Error message 2");
echo get_media_items($post_id, $errors);

Display media items only if the post has attachments

In this example, we first check if the post with ID 123 has any attachments. If it does, we display the media items.

$post_id = 123;
$errors = array();
$attachments = get_attached_media('image', $post_id);

if (!empty($attachments)) {
    echo get_media_items($post_id, $errors);
}

Display media items of the current post inside a loop

In this example, we display the media items of the current post inside a WordPress loop.

if (have_posts()) {
    while (have_posts()) {
        the_post();
        $post_id = get_the_ID();
        $errors = array();
        echo get_media_items($post_id, $errors);
    }
}

Display media items of all posts of a custom post type

In this example, we display the media items of all posts of a custom post type called ‘portfolio’.

$args = array(
    'post_type' => 'portfolio',
    'posts_per_page' => -1
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        $errors = array();
        echo get_media_items($post_id, $errors);
    }
}

wp_reset_postdata();