Getting first 20 words without excerpt

I’m working on my own custom theme (first custom WP work so I’m a real beginner) and need help in listing the first 20 words of a list of recent posts.

I managed to solve this with manual? excerpt but I would like to just get the first 20 words of the content, but not sure how to best do that. The application is in a list on my start page.

My current code looks like this

    <?php
    $cdRP = get_theme_mod('cd_recent_posts', '3');
    $args = array( 'numberposts' => $cdRP );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<div class="grid-cell"><a class="fpItems" href="' . get_permalink($recent["ID"]) . '">';
        if ( has_post_thumbnail( $recent["ID"]) ) {
            echo  '<div>' . get_the_post_thumbnail($recent["ID"],'thumbnail') . '</div>';
        }
        echo '<div>'
        . '<h3>' . $recent["post_title"] . '</h3>'

        . '</div></a></div>';
    }
    wp_reset_query();
?>

All of this happens outside the loop. I tried to find the answer in the forums, but failed, so sorry if this has been asked and answered before. Trying my best to learn to code this wonderful tool my self 🙂

3 Answers
3

Use wp_trim_words()

wp_trim_words( get_the_content(), 20 )

As you’re outside the main loop

wp_trim_words( $recent[ 'post_content' ], 20 )

If you want to apply the same filters as to the_content() in the main loop

wp_trim_words( apply_filters( 'the_content', $recent[ 'post_content' ] ), 20 )

Leave a Comment