Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

gorka.molero on "Turning IMGs into divs with background-image (preg_replace)"

$
0
0

Hey guys!

I'm trying something out but as I'm not versed in PHP it feels like smashing my head against random walls.

I need to alter the output of image tags. I want to replace the img tag for a div with a background image, to achieve sort of this effect.

I'm working around this function, in functions.php. This only takes the full image code and outputs it into the background-image url. I would need to extract the SRC.

function turnItIntoDiv( $content ) {

   // A regular expression of what to look for.
   $pattern = '/(<img([^>]*)>)/i';
   // What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
   $replacement = '<div class="full-image" style="background-image: url("$1")"></div>';

   // run preg_replace() on the $content
   $content = preg_replace( $pattern, $replacement, $content );

   // return the processed content
   return $content;
}

add_filter( 'the_content', 'turnItIntoDiv' );

Thank you all


Viewing all articles
Browse latest Browse all 8245

Trending Articles