Blog / WordPress/ Automatically Extract Post Content as Excerpt in WordPress

Automatically Extract Post Content as Excerpt in WordPress

WordPress截取文章内容做为文章摘要

An article excerpt is an important piece of information. Manually writing an excerpt for every post can be time-consuming, which is why WordPress's default excerpt feature sometimes falls short.

This post introduces a method to automatically extract part of the post content to use as the excerpt, with customizable length, to solve the tedious problem of manual excerpt writing.

Core Code

The following PHP snippet checks if a post has a manually written excerpt. If it does, it displays that; otherwise, it automatically extracts content from the post body.

<?php
if (has_excerpt()) {
    // If the post has a manual excerpt, output it.
    echo get_the_excerpt();
} else {
    // If no manual excerpt, extract from content.
    $raw_content = apply_filters('the_content', $post->post_content);
    $stripped_content = strip_tags($raw_content);
    $excerpt = mb_strimwidth($stripped_content, 0, 170, "…");
    echo $excerpt;
}
?>

Code Explanation

  • has_excerpt(): Checks if the current post has a manually written excerpt.
  • get_the_excerpt(): Retrieves the manual excerpt.
  • apply_filters('the_content', $post->post_content): Gets the raw post content and applies all filters associated with 'the_content', ensuring it matches front-end display.
  • strip_tags(): Removes all HTML tags to avoid code in the excerpt.
  • mb_strimwidth($string, $start, $width, $trimmarker): A multibyte-safe string truncation function.
    • $string: The string to truncate.
    • $start: Start position, usually 0.
    • $width: Maximum width in characters (e.g., 170).
    • $trimmarker: String appended after truncation (e.g., "…").

Important: The mb_strimwidth function requires the PHP mbstring extension to be enabled on your server for proper multibyte character handling.

How to Use

Copy the code into your WordPress theme's template files (e.g., index.php, archive.php, or content.php) where you want to display the excerpt, not directly in functions.php.

A more standard approach is to wrap the logic in a function and call it from your template:

// Define function in functions.php
function my_custom_excerpt($length = 170) {
    if (has_excerpt()) {
        return get_the_excerpt();
    } else {
        $content = apply_filters('the_content', get_the_content());
        $stripped = strip_tags($content);
        return mb_strimwidth($stripped, 0, $length, '…');
    }
}

// Call in template file (e.g., content.php)
<div class="entry-summary">
    <?php echo my_custom_excerpt(200); // Pass custom length ?>
</div>

This method is more flexible and adheres to WordPress development standards.

Post a Comment

Your email will not be published. Required fields are marked with *.