1
votes

I'm trying to create a simple WordPress plugin for the TinyMCE editor that adds a button to the editor bar, that when you click on this it inserts an image into the content, and I want this image to be clickable by the person reading the published and run some JavaScript when this occurs (basically just to open a new window with some specific sizing).

The problem I have is that TinyMCE strips the onClick event I add to the image hyperlink, so it doesn't work. I understand one way to fix this is to change the valid_elements section for TinyMCE, but this would involve anyone installing the plugin having to go and make those changes manually. Is there anyway to be able to run some JS when the image is clicked by the reader solely in my plugin?

1
What do you mean by "TinyMCE strips the onClick event"?user7881930

1 Answers

1
votes

Should be a matter of extending TinyMCE valid elements inside your own plugin. Here an example adding the image tag with all properties enabled:

add_filter( 'tiny_mce_before_init', function ( $init ) {
    $img = 'img[*]';
    if ( isset( $init['extended_valid_elements'] ) ) {
        $init['extended_valid_elements'] .= ',' . $img;
    } else {
        $init['extended_valid_elements'] = $img;
    }
    return $init;
});

I used the following when creating the TinyMCE button to insert a clickable <img> element into the post content:

ed.addButton( 'test_button', {
    title : 'Insert clickable image',
    image : '../wp-includes/images/smilies/icon_eek.gif',
    onclick : function() {
        ed.selection.setContent( '<img src="http://example.com/test.gif" onclick="alert()" />' );
    }
});