---
title: Media
description: MediaPress Media enhances media handling capabilities within the block editor, including attached media tracking, a scoped media library, and featured image variations.
url: https://developers.wpengine.com/docs/newsroom/mediapress/media/
image: https://developers.wpengine.com/og/docs/newsroom/mediapress/media.png
---

# Media

MediaPress Media enhances media handling capabilities within the block editor in a variety of ways.

This includes the concept of ‘attached media’, which includes any media used, or flagged for usage, within a specific post. By tracking media usage in this way, we are able to optimize the media library for improved performance at scale.

### Scoped Media Library

When browsing the core media library from within the block editor, only media that is ‘attached’ to the current post is displayed for selection, providing a more focused experience and improved performance within the core media modal. Search and filtering functionalities work as expected within this pool of media items, making it easier to find relevant content.

### Dedicated Media View

A dedicated ‘Media’ view is implemented for searching the media library. Here, media items can be attached and unattached from the current post, or uploaded directly to the post via drag-and-drop.

### Media Attachment and Protection

Uploading media to the post by any means within the block editor will automatically attach the media to the current post. Media items that are used within the post content, either within image blocks or as featured media, are marked as ‘in use’ within the media view and the ability to detach them from the post is blocked.

### Featured Image Variations (experimental)

Allows for editing ‘variations’ of the featured image, for use in different locations throughout a site. Each variation can have a specific aspect ratio, crop and/or URL to adjust or fully replace the main featured image.

Variations can be edited via the featured image area within the block editor, and variation information is stored as metadata under the key `mediapress_media_featured_image_variations`. This information can be used to generate crops or otherwise filter the post featured image.

We currently support both Photon (VIP) and Cloudflare image cropping via CDN URLs, and provide a filter for passing the crop information to other services.

Enable this experimental feature by setting the feature flag to `true`:

```php
add_filter( 'mediapress_media_featured_image_variations_flag' , '__return_true' );
```

Photon (VIP) cropping is enabled if the `WPCOM_VIP_USE_JETPACK_PHOTON` constant is `true`. This can also be controlled by the `mediapress_media_featured_image_variations_use_photon` filter.<!-- spell-checker:ignore WPCOM, JETPACK -->

Cloudflare cropping is enabled if the `mediapress_media_featured_image_variations_cloudflare_domain` filter is set.

Additional services can be used via the `mediapress_media_featured_image_variations_cropped_url` filter.

### Responsive crops example

In some instances you may want to use featured image crops but have different crops at different viewport sizes. For example landscape on mobile and portrait on desktop in a list of cards. This can be handled in your project, here we are using a block filter to render a picture element instead of the standard `img` tag, using the MediaPress util functions to access the crops.

```php
public function __construct() {
    add_filter( 'render_block', [ $this, 'featured_image_crops' ], 20, 2 ); // must run after mediapress filters
}


public function featured_image_crops( $block_content, $block ) {
    if ( 'core/post-featured-image' !== $block['blockName'] ) {
        return $block_content;
    }


    if ( ! isset( $block['attrs']['className'] ) ||
    ! str_contains( $block['attrs']['className'], 'has-ratio-variations' )
    ) {
        return $block_content;
    }


    preg_match( '/src="([^"]+)"/', $block_content, $matches );
    if ( empty( $matches[1] ) ) {
        return $block_content;
    }


    $variations = [
        'tall' => $this->get_variation_data( 'post-featured-tall' ),
        'wide' => $this->get_variation_data( 'post' ),
    ];


    foreach ( $variations as $variation ) {
        if ( empty( $variation['crop_data'] ) ) {
            return $block_content;
        }
    }


    $standard_src = $this->featured_image_variations->get_cropped_src(
        $variations['tall']['image_url'],
        $variations['tall']['crop_data'],
        $variations['tall']['width'],
        $variations['tall']['height']
    );


    $mobile_src = $this->featured_image_variations->get_cropped_src(
        $variations['wide']['image_url'],
        $variations['wide']['crop_data'],
        $variations['wide']['width'],
        $variations['wide']['height']
    );


    preg_match( '/alt="([^"]*)"/', $block_content, $alt_matches );
    $fallback_alt = ! empty( $alt_matches[1] ) ? $alt_matches[1] : get_the_title( get_the_ID() );


    $standard_alt = ! empty( $variations['tall']['alt_text'] ) ? $variations['tall']['alt_text'] : $fallback_alt;
    $mobile_alt   = ! empty( $variations['wide']['alt_text'] ) ? $variations['wide']['alt_text'] : $fallback_alt;


    $picture_element = sprintf(
        '<picture>
      <source srcset="%s" media="(min-width: 600px)" alt="%s">
      <img src="%s" alt="%s">
  </picture>',
        esc_url( $standard_src ),
        esc_attr( $standard_alt ),
        esc_url( $mobile_src ),
        esc_attr( $mobile_alt )
    );


    // Replace img tag with picture element
    return preg_replace( '/<img[^>]*>/i', $picture_element, $block_content );
}
```

## Additional Configuration

Media must be activated via the “MediaPress” settings page. No additional configuration is necessary.

## Filters/Actions

### PHP

#### Filters

##### `mediapress_media_supported_post_types`

Defines the post types on which the media functionality will be enabled.

**Default Value**

`[ 'post', 'page' ]`

**Parameters**

| Name       | Type  | Description              |
| ---------- | ----- | ------------------------ |
| post_types | array | Array of post type slugs |

**Usage**

```php
add_filter( 'mediapress_media_supported_post_types', 'my_plugin_add_media_support' );
function my_plugin_add_media_support( array $post_types ): array {
  $post_types[] = 'my_custom_post_type';
  return $post_types;
}
```

##### `mediapress_media_featured_image_variations_config`

Enables the customization or replacement of the featured image variations config.

**Parameters**

| Name                            | Type                             | Description                                              |
| ------------------------------- | -------------------------------- | -------------------------------------------------------- |
| config                          | `Array<string, VariationConfig>` | An array of variation config items keyed by variation ID |
| config\[key]                    | `string`                         | The variation ID (e.g. ‘article-lead’)                   |
| config\[value]                  | `VariationConfig`                | The variation configuration object                       |
| config\[value].label            | `string`                         | Display label for the variation (e.g. ‘Article Lead’)    |
| config\[value].aspectRatio      | `float`                          | Aspect ratio value (e.g. 1.777 for 16:9)                 |
| config\[value].aspectRatioLabel | `string`                         | Human readable aspect ratio (e.g. ‘16:9’)                |
| config\[value].style            | `'round'?`                       | Optional style modifier                                  |

**Usage**

```php
function my_filter( $config ) {
  $config['custom-crop'] = [
    'label'            => __( 'Custom Crop', 'mediapress' ),
    'aspectRatio'      => 3 / 2,
    'aspectRatioLabel' => '3:2',
  ];
  return $config;
}
```

##### `mediapress_media_featured_image_variations_cloudflare_domain`

Allows the domain to be set to use for cloudflare image cropping.

**Parameters**

| Name     | Type     | Description            |
| -------- | -------- | ---------------------- |
| orig_src | `string` | The original image src |

**Usage**

```php
add_filter( 'mediapress_media_featured_image_variations_cloudflare_domain', 'my_cloudflare_domain_filter' );
function my_cloudflare_domain_filter( $orig_src ) {
  return 'www.my-domain.com';
}
```

##### `mediapress_media_featured_image_variations_use_photon`

Defines if photon image cropping is enabled or not.

**Parameters**

| Name              | Type      | Description                         |
| ----------------- | --------- | ----------------------------------- |
| is_photon_enabled | `boolean` | If photon is enabled already or not |

**Usage**

```php
add_filter( 'mediapress_media_featured_image_variations_use_photon', 'my_use_photon_filter' );
function my_use_photon_filter( $is_photon_enabled ) {
  return false;
}
```

##### `mediapress_media_featured_image_variations_cropped_url`

Allows the changing of the final cropped image url.

**Parameters**

| Name                 | Type                   | Description                |
| -------------------- | ---------------------- | -------------------------- |
| src                  | `string`               | The cropped image src url  |
| orig_src             | `string`               | The original image src url |
| crop_values          | `Array<string, float>` | The crop values            |
| crop_values\[top]    | `float`                | The top crop values        |
| crop_values\[right]  | `float`                | The right crop values      |
| crop_values\[bottom] | `float`                | The bottom crop values     |
| crop_values\[left]   | `float`                | The left crop values       |
| width                | `float`                | The width of the image     |
| height               | `float`                | The height of the image    |

### JavaScript

#### Slotfills

Slotfills allow you to render custom content in various locations within the plugin, for example:

```js
import { Fill } from '@wordpress/components';
import domReady from '@wordpress/dom-ready';
import { registerPlugin } from '@wordpress/plugins';


domReady(() => {
  registerPlugin('my-plugin-slotfills', {
    render: () => (
      <Fill name="mediapress_media_search_filters_left">
        <div>This will render on the left side of the search filters</div>
      </Fill>
    ),
  });
});
```

##### `mediapress_media_search_filters_left`

Allows rendering of content in the left side of media search filters.

#### Filters

##### `mediaPress.media.postMediaIds`

Allows for the filtering of the media IDs contained within a post.

This value will be used to update the attached media to signify which images are currently ‘in use’ within a post. This will ensure they are added to the attached media meta, and also flagged as ‘in use’.

The filter receives the current post meta object as a parameter, to simplify inclusion of media IDs from any custom meta values.

**Parameters**

| Name         | Type         | Description                  |
| ------------ | ------------ | ---------------------------- |
| postMediaIds | `Array<int>` | An array of attachment IDs   |
| meta         | `Object`     | The current post meta object |

**Usage**

```js
addFilter(
  'mediaPress.media.postMediaIds',
  `my-plugin/add-custom-fields-to-post-media`,
  (postMediaIds, meta) => {
    const additionalMediaIds = [];


    if (meta.social_image) {
      additionalMediaIds.push(parseInt(meta.social_image, 10));
    }


    return [...postMediaIds, ...additionalMediaIds];
  },
);
```

##### `mediaPress.media.postMediaBlocks`

Allows for the filtering of the blocks and attributes to check when detecting post media.

This value will be used to update the attached media to signify which images are currently ‘in use’ within a post. This will ensure they are added to the attached media meta, and also flagged as ‘in use’.

The `attributes` property supports various syntax for checking block attributes, depending on how they are stored on your block, see the examples for more info.

**Parameters**

| Name                           | Type                             | Description                               |
| ------------------------------ | -------------------------------- | ----------------------------------------- |
| postMediaBlocks                | `Array<{blockName, attributes}>` | An array of blocks to check for media IDs |
| postMediaBlocks\[0].blockName  | `string`                         | The name of the block to check            |
| postMediaBlocks\[0].attributes | `Array<string\|Array<string>>`   | The block attributes to check             |

**Usage**

```js
addFilter(
  'mediaPress.media.postMediaBlocks',
  `my-plugin/add-custom-blocks-to-post-media`,
  (postMediaBlocks, meta) => {
    return [
      ...postMediaBlocks,
      {
        blockName: 'custom/single-attribute',
        attributes: ['id'], // e.g: { id: 1 }
      },
      {
        blockName: 'custom/multiple-attributes',
        attributes: ['id', 'avatarId'], // e.g: { id: 1, avatarId: 2 }
      },
      {
        blockName: 'custom/nested-attributes',
        attributes: ['media.id'], // e.g: { media: { id: 1 } }
      },
      {
        blockName: 'custom/array-of-ids',
        attributes: [['ids']], // e.g: { ids: [1, 2, 3] }
      },
      {
        blockName: 'custom/array-of-nested-ids',
        attributes: [['images', 'id']], // e.g: { images: [ { id: 1 }, { id: 2 }, {id: 3 } ] }
      },
      {
        blockName: 'custom/complex-example',
        attributes: [['mediaItems', 'image.id'], 'backgroundImage.id'],
        // This checks two attributes on a custom block
        // 1. mediaItems -  an array containing image objects
        // 2. backgroundImage - a single image object
        // e.g: { mediaItems: [ { image: { id: 1 } }, { image: { id: 2 } } ], backgroundImage: { id: 3 } }
      },
    ];
  },
);
```

##### `mediaPress.media.mediaItem`

Allows wrapping the `MediaItem` component with a higher-order component (HOC). Use this to augment or decorate the media grid/list item — for example, to render an overlay badge on matching attachments.

**Parameters (HOC signature)**

| Name             | Type        | Description                                     |
| ---------------- | ----------- | ----------------------------------------------- |
| WrappedComponent | `Component` | The original (or previously-filtered) MediaItem |

**Usage**

```js
import { addFilter } from '@wordpress/hooks';


addFilter(
  'mediaPress.media.mediaItem',
  'my-plugin/media-item',
  (WrappedComponent) =>
    ({ mediaItem, ...props }) => (
      <>
        <WrappedComponent mediaItem={mediaItem} {...props} />
        {mediaItem.my_custom_flag && <MyBadge />}
      </>
    ),
);
```

##### `mediaPress.media.mediaInfo`

Allows wrapping the `MediaInfo` panel component with a higher-order component (HOC). Use this to augment or decorate the info panel — for example, to render an overlay badge on matching attachments. The HOC receives `attachmentId` as a prop; fetch the attachment record yourself (e.g. via `useEntityRecord`, which core-data caches) to read any fields you need.

**Parameters (HOC signature)**

| Name             | Type        | Description                                     |
| ---------------- | ----------- | ----------------------------------------------- |
| WrappedComponent | `Component` | The original (or previously-filtered) MediaInfo |

**Usage**

```js
import { useEntityRecord } from '@wordpress/core-data';
import { addFilter } from '@wordpress/hooks';


addFilter(
  'mediaPress.media.mediaInfo',
  'my-plugin/media-info',
  (WrappedComponent) =>
    ({ attachmentId, ...props }) => {
      const { record } = useEntityRecord(
        'postType',
        'attachment',
        attachmentId,
      );


      return (
        <>
          <WrappedComponent attachmentId={attachmentId} {...props} />
          {record?.my_custom_flag && <MyBadge />}
        </>
      );
    },
);
```

## Was this helpful?

Thanks for the feedback!

```json
{"@context":"https://schema.org","@graph":[{"@type":"WebSite","@id":"https://developers.wpengine.com/#website","name":"WP Engine Product Documentation","url":"https://developers.wpengine.com/","description":"Resources for developing, deploying, and scaling on WP Engine.","inLanguage":"en-US","keywords":["API documentation","product documentation","headless WordPress","managed WordPress hosting"],"publisher":{"@id":"https://wpengine.com/#organization"}}]}
```
