Using Regex code to add code before each image
-
I’ve been trying to solve this issue for quite a while with no luck. I’m not very good with programming but still trying to have a crack.
My setup is I’ve enabled users to post topics frontend (just like this form) but with the “img” quicktag enabled. So, users can insert an image link within the post.
My ultimate goal is to add a link to each image and the href linking to the images src.
So eg. my current output for images is
<img src="link-to-image.jpg">
But what I’d like to achieve is
<a href="link-to-image.jpg"><img src="link-to-image.jpg"></a>
My only luck so far was by using the regex code found here: https://www.ads-software.com/support/topic/add-code-before-each-image?replies=6
I’ve tried many different ways including functions like: image_send_to_editor, get_image_tag, $replacement, $pattern but nothing so far has made any changes to the image markup like it has with the regex code above.
I’ve updated this section of the code to add a span before image linking to the post thumbnail attachment, but how can i achieve to link each image to its full src within the post using this regex code:
// If we get any hits then put the code before and after the img tags if ( $mh_matches ) {; for ( $mh_count = 0; $mh_count < count( $mh_matches[0] ); $mh_count++ ) { // Old img tag $mh_old = $mh_matches[0][$mh_count]; // Get the img URL, it's needed for the button code $mh_img_url = $mh_matches[1][$mh_count]; // Put together the pinterest code to place before the img tag $mh_pinterest_code = '<span class="test"><a href="' . ( wp_get_attachment_url( get_post_thumbnail_id() ) ) . '">'; // Replace before the img tag in the new string $mh_new = preg_replace( '/^/' , $mh_pinterest_code , $mh_old ); // After the img tag $mh_new = preg_replace( '/$/' , '</a></span>' , $mh_new ); // make the substitution $content = str_replace( $mh_old, $mh_new , $content ); } } return $content; }
Full code here: https://pastebin.com/PJ9S4zWe
Thanks
- The topic ‘Using Regex code to add code before each image’ is closed to new replies.