Advertisement
salmancreation

How to add automatic class in image for wordpress post

Jul 1st, 2015
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. <?php
  2. //----------------------------------------------------------/
  3. // responsive images [ 1) add img-responsive class 2) remove dimensions ]
  4. //----------------------------------------------------------/
  5.  
  6. function bootstrap_responsive_images( $html ){
  7. $classes = 'img-responsive'; // separated by spaces, e.g. 'img image-link'
  8.  
  9. // check if there are already classes assigned to the anchor
  10. if ( preg_match('/<img.*? class="/', $html) ) {
  11. $html = preg_replace('/(<img.*? class=".*?)(".*?\/>)/', '$1 ' . $classes . ' $2', $html);
  12. } else {
  13. $html = preg_replace('/(<img.*?)(\/>)/', '$1 class="' . $classes . '" $2', $html);
  14. }
  15. // remove dimensions from images,, does not need it!
  16. $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
  17. return $html;
  18. }
  19. add_filter( 'the_content','bootstrap_responsive_images',10 );
  20. add_filter( 'post_thumbnail_html', 'bootstrap_responsive_images', 10 );
  21.  
  22.  
  23.  
  24. Wordpress Bootstrap 3 responsive images
  25.  
  26. since you need to have it for all of your post images, then you need to add a hook for the content and add
  27.  
  28. function add_responsive_class($content){
  29.  
  30. $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
  31. $document = new DOMDocument();
  32. libxml_use_internal_errors(true);
  33. $document->loadHTML(utf8_decode($content));
  34.  
  35. $imgs = $document->getElementsByTagName('img');
  36. foreach ($imgs as $img) {
  37. $img->setAttribute('class','img-responsive');
  38. }
  39.  
  40. $html = $document->saveHTML();
  41. return $html;
  42. }
  43. now add the hook to the content
  44.  
  45. add_filter ('the_content', 'add_responsive_class');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement