0

I have created a function it wraps all image tag inside a div, but I want to apply it only for the post but my function wraps the page images inside a div also.

// Wrap  img into div
function wrapDivToImage($content) {

    $pattern = '/(<img([^>]*)>)/i';   
    $replacement = '<div class="well text-center">$1</div>';    
    $content = preg_replace($pattern, $replacement, $content);   
    return $content;
}

add_filter('the_content', 'wrapDivToImage');

And my second query is how stop wrapping div to image tag if image tag has an attribute id="nowrap" even it is a post?

0

You have the global WP_Post object available so you can look the post type like this:

function wrap_post_images_to_div( $content ) {
    if ( get_post()->post_type === 'post' ) {
        $pattern = '/(<img([^>]*)>)/i';   
        $replacement = '<div class="well text-center">$1</div>';    
        $content = preg_replace( $pattern, $replacement, $content );
    }
    return $content;
}
add_filter( 'the_content', 'wrap_post_images_to_div' );

You can use the preg_replace_callback instead to filter the matches with certain ids from the matches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.