Change Output for Images in Content

I want to wrap some html (divs and classes) around the tag (to create the appearance of photo corners by way of an image sprite).

Basically, I want to re-write all tags added by WP in the content by way of some code in my functions file from this:

<a href="#link"><img src="image.jpg" class="someclass"></a>

to this:

<div class="featured-img">
    <a rel="#lightbox" href="#link" class="#lightboxclass"><img src="image.jpg" class="someclass"></a>
    <div class="corner-nw"></div>
    <div class="corner-ne"></div>
    <div class="corner-sw"></div>
    <div class="corner-se"></div> 
</div>

I want this done after the page has been added/edited by me or anyone else adding content. I tried using wp_get_attachment_image with the function below, and it added the html ONLY when adding the image the first time into the edit content screen. Plus, when the image itself is dragged around inside the edit box, or possibly removed, remnants of the html are messed up.

    function image_corners( $html, $id, $alt, $title ){
    $html="<div class="featured-img"><img src="" . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" '.$hwstring.'class="'.$class.'" /><div class="corner-nw"></div><div class="corner-ne"></div><div class="corner-sw"></div><div class="corner-se"></div></div>';
    return $html;
    }
add_filter('wp_get_attachment_image','image_corners',10,4);

It seems like every option I look at with a filter or a hook only adds it during the add-image step in the edit screen. Am I mistaken on this? I’d be fine with a jquery option to change the html on/after page load, but I’m not quite sure how to write that, and not sure if that is necessary? Any help is appreciated!

1 Answer
1

One way is to do this dynamically:

function do_the_replacements($matches){

  // $matches[0] = full string
  // $matches[1] = link attributes
  // $matches[2] = link contentes (the image)

  // change 'someclass' here...
  if(strpos($matches[2], 'someclass') !== false){
    return '
      <div class="featured-img">
        <a '.$matches[1].'>'.$matches[2].'</a>
        <div class="corner-nw"></div>
        <div class="corner-ne"></div>
        <div class="corner-sw"></div>
        <div class="corner-se"></div>
      </div>
    ';

  }

  // no matches, leave it as it is
  return $matches[0];
}

function my_content_filter($content){
  return
    preg_replace_callback('#\<a(.+?)\>(.+?)\<\/a\>#s', 'do_the_replacements', $content);
}

add_filter('the_content', 'my_content_filter');

Leave a Comment