Skip to content

Instantly share code, notes, and snippets.

@kisabelle
Last active January 1, 2016 18:58
Show Gist options
  • Save kisabelle/8186897 to your computer and use it in GitHub Desktop.
Save kisabelle/8186897 to your computer and use it in GitHub Desktop.
Filter the_content() to add Pinterest button code, by Jan Dembowski.
<?php
/*
Plugin Name: Pinterest Img Tag Button
Description: This will wrap images in the_content with Pinterest Button code
Author: Jan Dembowski
Author URI: http://blog.dembowski.net/
Version: 0.5
From http://wordpress.org/support/topic/add-code-before-each-image
*/
add_filter( 'the_content' , 'mh_wrap_image' , 15 );
function mh_wrap_image( $content ) {
// Regex to find all <img ... > tags
$mh_img_regex1 = "/\<img [^>]*src=\"([^\"]+)\"[^>]*>/";
// Regex to find all <a href"..."><img ... ></a> tags
$mh_img_regex2 = "/<a href=.*><img [^>]*src=\"([^\"]+)\"[^>]*><\/a>/";
// Populate the results into 2 arrays
preg_match_all( $mh_img_regex1 , $content, $mh_img );
preg_match_all( $mh_img_regex2 , $content, $mh_matches );
// The second array will be a subset of the first so go through
// each element and delete the duplicates in the first.
$i=0;
foreach ( $mh_img[0] as $mh_img_count ) {
$i2=0;
foreach ( $mh_matches[0] as $mh_matches_count ) {
if ( strpos($mh_matches_count, $mh_img_count ) ){
unset( $mh_img[0][$i] );
unset( $mh_img[1][$i] );
$i2++;
break;
}
$i2++;
}
$i++;
}
// There is almost certainly a better way to do this.
// Append the no links array to the $mh_matches array.
$i=0;
$mh_start = count( $mh_matches[0] );
foreach ( $mh_img[0] as $mh_img_count ) {
$mh_matches[0][ $mh_start + $i ] = $mh_img_count;
$i++;
}
$i=0;
foreach ( $mh_img[1] as $mh_img_count ) {
$mh_matches[1][ $mh_start + $i ] = $mh_img_count;
$i++;
}
// 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="pinterest-button"><a href="http://pinterest.com/';
$mh_pinterest_code .= 'pin/create/button/?url=' . urlencode( get_permalink() );
$mh_pinterest_code .= '&media=' . $mh_img_url . '&description=';
$mh_pinterest_code .= urlencode( get_the_title() ) . '" class="pin-it-post"></a>';
// 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( '/$/' , '</span>' , $mh_new );
// make the substitution
$content = str_replace( $mh_old, $mh_new , $content );
}
}
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment