• I added a function to functions.php, which adds an onclick event to image tags on pages:

    function click_image($insert)
    {
    if(preg_match('/^(<img)/', $insert))
    $insert = str_replace('<img', '<img onclick="PopUp(this)"', $insert);
    return $insert;
    }
    add_filter('media_send_to_editor', 'click_image');

    This works just as it was meant to…except that it won’t work on photos inserted with captions. Those come in embedded inside DIVs; I don’t know why this should make a difference, but I wrote a second function to take care of it:

    function click_image_again($insert)
    {
    if(preg_match('/^(<div.*(<img).*(</div>$)/', $insert))
    $insert = str_replace('<img', '<img onclick="PopUp(this)"', $insert);
    return $insert;
    }
    add_filter('media_send_to_editor', 'click_image_again');

    …but this does nothing. I thought, maybe since it shows in the editor not as a DIV, but as a shortcode, I’d do it that way:

    function click_image_again($insert)
    {
    if(preg_match('/^([caption.*(<img).*([/caption]$)/', $insert))
    $insert = str_replace('<img', '<img onclick="PopUp(this)"', $insert);
    return $insert;
    }
    add_filter('media_send_to_editor', 'click_image_again');

    Again, nothing. The only thing I can think of is that I screwed up the string replace somehow, but I can’t see what’s wrong. Does anyone have an idea?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    I agree that there is likely a flaw in your regexp. Rather than chase after that flaw, you might consider instead overriding the [caption] shortcode handler so that it results in the desired HTML from the start instead of trying to fix it up after the fact.

    Use the ‘img_caption_shortcode’ filter to override. Whatever your callback returns becomes the shortcode output. This does mean you need to reinvent what the shortcode handler does to a large extent in order to simply insert an onclick attribute. I think this approach will be more reliable and you can borrow from the original source code for the bulk of what your callback needs to do. Depending on your needs, some chunks of the original source code may not be necessary, so your version could turn out to be a little more efficient.

Viewing 1 replies (of 1 total)
  • The topic ‘Adding onclick event to image tags only half-working’ is closed to new replies.