limit the words in the post content and add read more link

I always have the same problem with post excerpt, post content. There’re various hooks and functions for this purpose, like @kaiser pointed out. But sometimes they don’t do exactly what I want.

Here’s my solution, I write my own function that take the post content, and truncate it into specified number of words:

function wpse69204_excerpt( $num_words = 20, $ending = '...', $post_id = null )
{
    global $post;

    // Truncate post content
    $current_post = $post_id ? get_post( $post_id ) : $post;
    $excerpt = strip_shortcodes( $current_post->post_content );
    $excerpt = wp_trim_words( $excerpt, $num_words, $ending );

    // Read more link
    $excerpt .= '<a href="' . get_permalink( $post ) . '" title="">Continue reading...</a>';

    return $excerpt;
}

Leave a Comment