How to remove images from showing in a post with the_content()?

Trying to learn more about creating my own themes and not using any plugins I wanted an ability to display all the images in a post excluding the thumbnail in my single-foobar.php file and I can do that with:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();    

$thumb_ID = get_post_thumbnail_id( $post->ID );
 $args = array(
   'post_type' => 'attachment',
   'numberposts' => -1,
   'post_status' => null,
   'post_parent' => $post->ID,
   'exclude' => $thumb_ID
  );

$attachments = get_posts( $args );
 if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
       echo '<div class="portproject">';
       $image_res = wp_get_attachment_image( $attachment->ID, ' img-responsive' );
       echo $image_res;
       echo '</div>';
      }
 }
 else { ?>
    <span> No pictures loaded at this time</span>
 <?php } endwhile; endif; ?>

However, when I apply my static HTML and then try to call get_the_content() with:

<?php 
$content = get_the_content();
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);          
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>

it removes the images but leaves a (image) in the post with spaces then displays the remaining text. I did find a similar question but it suggests using get_the_content() but that strips all the styling from the post. So my question is how can I strip images from the_content()? I did find “Getting the_content WordPress Text Only (Strip Out Image Tags)” from my searches but that still uses the get_the_content() approach.

3 Answers
3

Try removing (image), like this:

<?php 
$content = get_the_content();
$content = preg_replace("/<img[^>]+\>/i", " ", $content);          
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>

Leave a Comment