Using WordPress ‘get_media_states()’ PHP function

The get_media_states() WordPress PHP function retrieves an array of media states from an attachment.

Usage

To use the get_media_states() function, simply pass a WP_Post object representing the attachment as an argument.

$media_states = get_media_states( $post );

Parameters

  • $post (WP_Post) – The attachment to retrieve states for.

More information

See WordPress Developer Resources: get_media_states()

Examples

Display Media States for an Attachment

This example displays the media states for a specific attachment with ID 123.

// Get the attachment post object
$attachment = get_post( 123 );

// Get the media states for the attachment
$media_states = get_media_states( $attachment );

// Output the media states as a comma-separated list
echo implode( ', ', $media_states );

List All Attachments with Their Media States

This example lists all attachments and their media states.

// Query all attachments
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1 );
$attachments = get_posts( $args );

// Loop through attachments and display their media states
foreach ( $attachments as $attachment ) {
    $media_states = get_media_states( $attachment );
    echo '<p><strong>' . $attachment->post_title . ':</strong> ' . implode( ', ', $media_states ) . '</p>';
}

This example shows the media states for featured images in a list of posts.

// Query all posts
$args = array( 'post_type' => 'post', 'posts_per_page' => -1 );
$posts = get_posts( $args );

// Loop through posts and display the media states of their featured images
foreach ( $posts as $post ) {
    $featured_image_id = get_post_thumbnail_id( $post->ID );
    $attachment = get_post( $featured_image_id );
    $media_states = get_media_states( $attachment );
    echo '<p><strong>' . $post->post_title . ':</strong> ' . implode( ', ', $media_states ) . '</p>';
}

Filter Attachments by Media State

This example filters attachments by a specific media state, such as “Header Image”.

// Query all attachments
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1 );
$attachments = get_posts( $args );

// Loop through attachments and display only those with the "Header Image" media state
foreach ( $attachments as $attachment ) {
    $media_states = get_media_states( $attachment );
    if ( in_array( 'Header Image', $media_states ) ) {
        echo '<p><strong>' . $attachment->post_title . ':</strong> ' . implode( ', ', $media_states ) . '</p>';
    }
}