2

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.

9

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;
?>
  • 1
    In cased images with <a> tag then content in arrived blank <a></a> tags. – ravi patel May 19 '16 at 11:54
4

The method I prefer to use is just a bit shorter then the previous answer.

<php $myExcerpt = wp_trim_words( get_the_content(), 20, '' ) ; 
echo $myExcerpt ; ?>

The WordPress function wp_trim_words() returns only text (no images).

wp_trim_words ( string $text, int $num_words = 55, string $more = null )

  • That's not really true, wp_trim_words returns also images – spacebiker Oct 10 '18 at 11:37

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.