Skip to content

Filter Image Block attributes (or markup) when image is selected in Media Library #8472

Closed as not planned

Description

One of the plugins I work on, Tasty Pins, offers the ability to add "Pinterest Text" to an image (related #8473).

In the Classic Editor, the user can edit their Pinterest Text in the Media Library:

image

When the image is inserted into the post, the Pinterest Text is included as a data-pinterest-description data attribute:

image

Even though all of this interaction is clientside, a plugin can modify the <img> image markup sent to the editor via the image_send_to_editor filter (ref):

/**
 * Append Pinterest Text to markup sent to editor
 *
 * @param string $html The image HTML markup to send.
 * @param int    $id   The attachment id.
 * @return string
 */
public static function filter_image_send_to_editor( $html, $id ) {
	if ( ! empty( $_POST['props']['tp_pinterest_text'] ) ) {
		$html = str_replace( '<img ', '<img data-pin-description="' . esc_attr( wp_unslash( $_POST['props']['tp_pinterest_text'] ) ) . '" ', $html );
	}
	if ( ! empty( $_POST['props']['tp_pinterest_nopin'] ) ) {
		$html = str_replace( '<img ', '<img data-pin-nopin="true" ', $html );
	}
	return $html;
}

What's the best way to achieve equivalent behavior in Gutenberg?

One idea, albeit not necessarily a good one, is to make onSelectImage filterable:

onSelectImage( media ) {
if ( ! media || ! media.url ) {
this.props.setAttributes( {
url: undefined,
alt: undefined,
id: undefined,
caption: undefined,
} );
return;
}
this.props.setAttributes( {
...pick( media, [ 'alt', 'id', 'caption', 'url' ] ),
width: undefined,
height: undefined,
} );
}

onSelectImage seems to be common across Image, Cover Image, and Gallery Blocks. Other approaches?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Backwards CompatibilityIssues or PRs that impact backwards compatability[Feature] BlocksOverall functionality of blocks[Feature] ExtensibilityThe ability to extend blocks or the editing experience[Feature] MediaAnything that impacts the experience of managing media[Type] EnhancementA suggestion for improvement.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions