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.

3 Answers 3

10

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
  • 1
    In cased images with <a> tag then content in arrived blank <a></a> tags.
    – Ravi Patel
    May 19, 2016 at 11:54
5

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 )

2
  • That's not really true, wp_trim_words returns also images
    – spacebiker
    Oct 10, 2018 at 11:37
  • This worked for me - thanks for taking the time :-) Jul 28, 2022 at 16:24
0

almost the same than derekshrink directely fom the WordPress dev.

<?php echo wp_trim_words( get_the_content(), 40, '...' ); ?>

you can change the number of word you want to show

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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