Retrieve a specific number of words from post_Content

I would to retrieve a specific number of words from post_content, but I don’t want the tags stripped.

I was using wp_trim_words() before I realised that all my images are being removed, so I need an alternative way of doing it.

Solutions Collecting From Web of "Retrieve a specific number of words from post_Content"

I don’t think there is an excerpt type function that let you keep images. But there is functions to do what you want to do.

First you need to set up your excerpts. In your content.php file change

<?php if ( is_search() ) : ?>


<?php if ( is_search() || is_paged() ) : ?>


     function pietergoosen_excerpt_175_words( $length ) {
    return 175;
add_filter( 'excerpt_length', 'pietergoosen_excerpt_175_words' );

to set your excerpt length if you need anything other than the wordpress default of 55 words

The following functions will add the first image of your post to the excerpt and keep its aspect ratio. Add to functions.php

 function pietergoosen_get_first_image() {
        global $post;
        $first_img = '';
        if( $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches))
        $first_img = $matches [1] [0];

        return $first_img;

function pietergoosen_check_if_url_exist($url) {
    $headers = wp_get_http_headers($url);

    if (!is_array($headers)) :
        return FALSE;
    elseif (isset($headers["content-type"]) && (strpos($headers["content-type"],"image") !== false)) :
        return TRUE;
    else :
        return FALSE;
function pietergoosen_adjust_image_size($image, $alt, $newwidth, $newheight) {
    if (!file_exists($image) && !pietergoosen_check_if_url_exist($image)) return '';
    list($width, $height, $type, $attr) = getimagesize($image);
    if (!$width || !$height) return '';

    if ($newwidth)
        $newheight = intval($newwidth/$width * $height);
        $newwidth = intval($newheight/$height * $width);
    return '<img src="' . $image . '" width=' . $newwidth . ' height='. $newheight . ' alt=' . $alt . '/>';

Now add the following lines

<div class="alignleft-excerpt">
        <a href="<?php echo pietergoosen_get_first_image() ?>" title="<?php printf( the_title_attribute( 'echo=0' ) ); ?>" rel="lightbox">
          <?php echo pietergoosen_adjust_image_size(pietergoosen_get_first_image(), get_the_title(), 250, 0); ?>

just above

<?php the_excerpt(); ?>

in content.php. To set a personal size for your image, just set the value = 250 in the last set of code to any size you want. Keep the value = 0 as is. This is to keep the aspect ratio of your image.

Here are some styling to set padding

  .alignleft-excerpt img{
    padding-right: 10px;
    padding-right: 0.71rem; 
    padding-top: 6px; 
    padding-top: 0.42857143rem; 

.alignleft-excerpt {
    float: left;

Hope this helped.