WordPress developers often seek to refine and personalize the content display on their websites. A common area for customization is the excerpt of posts. The default the_excerpt()
function in WordPress provides a summary of a post by truncating the content to a specified number of words, often leading to incomplete sentences. In this blog post, I will detail a method to customize the_excerpt()
within a plugin to ensure excerpts end with a full stop or at the end of a sentence.
The Importance of Full-Sentence Excerpts
Excerpts that end mid-sentence can disrupt the reader’s flow and may not provide a complete picture of the post. By ensuring that excerpts end with a full stop or at the end of a sentence, you create a more engaging and informative summary for your readers.
Customizing the Excerpt in a Plugin
Instead of modifying the theme’s functions.php
file, integrating this customization into a plugin makes it theme-independent and portable. Here’s how you can achieve this:
- Creating a Custom Excerpt Function:
function custom_excerpt_with_full_sentence() {
$content = get_the_content('');
$content = strip_shortcodes($content);
$content = wp_strip_all_tags($content);
// Set the desired length of the excerpt
$excerpt_length = 35; // Adjust as needed
// Split content into sentences
$sentences = preg_split('/(.|?|!)("|'|)|]|s)*s/', $content, -1, PREG_SPLIT_NO_EMPTY);
// Build the excerpt from complete sentences
$excerpt = '';
foreach ($sentences as $sentence) {
if (str_word_count($excerpt . $sentence) <= $excerpt_length) {
$excerpt .= $sentence . '. ';
} else {
break;
}
}
// Clean up the excerpt
$excerpt = trim($excerpt);
$excerpt = rtrim($excerpt, ' .,!?:;');
return $excerpt;
}
In this function:
- The content is split into sentences.
- Sentences are concatenated until the word count limit is reached.
- The excerpt is trimmed and formatted.
- Integrating Custom Excerpt with WordPress Hooks:
function custom_excerpt_hook($excerpt) {
ob_start();
echo '<p>' . custom_excerpt_with_full_sentence() . '.</p>';
return ob_get_clean();
}
add_filter( 'the_excerpt', 'custom_excerpt_hook' );
- The
custom_excerpt_hook
function:- Captures the output of the custom excerpt function.
- Wraps it in a paragraph tag.
- Returns the formatted excerpt.
Benefits of Using a Plugin for Custom Excerpts
- Theme Independence: Customizations remain intact regardless of theme changes.
- Reusability: The plugin can be used across multiple WordPress sites.
- Easier Maintenance: Updates to the excerpt logic can be managed within the plugin.
Customizing the excerpt functionality in WordPress to ensure excerpts end with complete sentences enhances the readability and appearance of your website. By implementing this customization as a plugin, you add a layer of flexibility and maintainability to your WordPress site. This approach ensures that your excerpts are informative, concise, and contextually complete.