WordPress Tutorials

Understanding the_excerpt and the_content

By November 28, 2020No Comments

When displaying a teaser of your posts or pages there are two options that are seemingly popular. While its such a simple concept I’ll admit that it really beat me up a few times before I understood it clearly.

the_content is for pulling the content into a page. You’ll get the entire thing!

the_excerpt does exactly what it claims to… It displays excerpted content from a post or page.

the_excerpt counts a defaulted 55 words out of your content…that’s right, content and displays it as a kind of teaser. Should you fill out the excerpt field in the post or page’s administration page, then that instead will be displayed and will override the default content word count.

What’s that? You’d like to change the 55 word count you say?

The following code will change the excerpt length to 20… site-wide. (the 999 is priority, leave it be)

<?php 
function max_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'max_excerpt_length', 999 );
?>

What about a specific excerpt length here and a different length specified later?

This snippet will create a function that allows you to call a echo get_excerpt(#):

<?php
function get_excerpt($count){
    $permalink = get_permalink($post->ID);
    $excerpt = get_the_content();
    $excerpt = strip_tags($excerpt);
    $excerpt = substr($excerpt, 0, $count);
    $excerpt = substr($excerpt, 0, strripos($excerpt, " "));
    $excerpt = $excerpt.'... <a href="'.$permalink.'">more</a>';
    return $excerpt;
}
echo get_excerpt(125);
?>

For a great example of changing your excerpted content’s “More…” link to something better like “Read This Now!” or “I Can’t Believe You Haven’t Read This Yet” check out this code block:

function bones_excerpt_more($more) {
    global $post;
    // edit here if you like
    return '... <a href="'. get_permalink($post->ID) . '" title="Read '.get_the_title($post->ID).'">Read more &raquo;</a>';
}
add_filter('excerpt_more', 'bones_excerpt_more');

Leave a Reply