• I’m working on re-designing a theme to suit my needs, but I am not familiar with PHP, and as such not at all with the WP API.

    I recently added a small plugin to unwrap images from the <p> tag in posts, so I can have more control over the width. I see some various versions of it on the web (raw of the one I use)

    Now what I need is basically a div with a custom class to wrap around the image. Basically change what used to be the <p> wrapping around the image to be a div with an class. Need it for layout arrangement.

    Can someone help me with this please?

    • This topic was modified 8 years, 5 months ago by bcworkz. Reason: removed "help needed" from title - everyone needs help here
Viewing 2 replies - 1 through 2 (of 2 total)
  • If you are customizing the theme you will absolutely need some basic PHP syntax knowledge and an understanding of the WordPress core functionality is a MUST.

    to remove the p tags from images you can add this to your functions.php file

    
    // remove the p from around imgs (http://css-tricks.com/snippets/wordpress/remove-paragraph-tags-from-around-images/)
      function filter_ptags_on_images($content){
         return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
      }
    add_filter('the_content', 'filter_ptags_on_images');
    

    and this function will add a div around all images inside of posts

    
    function addDivToImage( $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="yourClass">$1</div>';
    
       // run preg_replace() on the $content
       $content = preg_replace( $pattern, $replacement, $content );
       return $content;
    }
    
    add_filter( 'the_content', 'addDivToImage' );
    

    A quick Google would have returned both solutions for you.

    Thread Starter MartinHaslien

    (@martinhaslien)

    @jaycbrf thanks, but if I have a caption with the image it doesn’t ecapsulate it, it ends up outside the wrap.

    I had the script for removing <p> tag (linked in OP) and found that through Google. Didn’t find anything working for the <div> wrap.

    I can read some PHP as I am on my way learning. The edits to the theme is mostly CSS related.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Pre-wrap images in posts’ is closed to new replies.