0

Using the filter wp_get_attachment_image_attributes I'm able, for example, to add an attribute to image attachments:

function my_filter( $attr, $attachment, $size )
{
    $attr['data-custom'] = 'hello';

    return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'my_filter', 10, 3 );

However this filter does not affects imgs in posts.

I already managed to do this with image_send_to_editor filter, but this way the attributes become "hard-coded" into the post's source so I'm not satisfied with this approach.

Is there a way to add/edit posts images' attributes dinamically as the imgs are rendered into the page source?

In other words, is there a way to extend wp_get_attachment_image_attributes to images in posts?

3
  • Did you try by filtering the_content for img tag?
    – Fayaz
    Jan 28, 2017 at 13:38
  • At the end (see my answer) I ended filtering the_content. But I identified images via string parsing. Is there a way to get and edit just imgs ?
    – Paolo
    Jan 28, 2017 at 13:43
  • Another approach is to add a new button to the editor that opens the media window and inserts your own custom shortcode for images. You can then insert whatever markup you want when the_content is rendered and your shortcode function executes.
    – Milo
    Jan 28, 2017 at 16:49

1 Answer 1

0

There is no such filter to do that directly.

The only way is intercept the post's content and modify it:

add_filter( 'the_content', 'FilterImages', 0 );
function FilterImages( $content )
{
    // parse $content looking for <img .... />
    // modify $content if it needs to be modified

    return $content;
}

I managed to do what I needed to do with some string manipulation.

I guess also DOMElement can be used if the content manipulation task is not trivial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.