Blog / WordPress/ How to Limit Post Title and Excerpt Length in WordPress

How to Limit Post Title and Excerpt Length in WordPress

WordPress截取文章内容字数和文章标题字数

This post explains several methods to limit the character or word count of post titles and excerpts in WordPress. These techniques are useful for archive pages (like the homepage or category pages) to maintain a clean, consistent layout.

Method 1: Using the WordPress Function wp_trim_words()

The built-in wp_trim_words() function is the safest and most integrated way to trim content by word count.

<?php
// Trim post content to 80 words
echo wp_trim_words( get_the_content(), 80 );
// Trim the manual excerpt to 80 words
echo wp_trim_words( get_the_excerpt(), 80 );
// Trim the post title to 30 words
echo wp_trim_words( get_the_title(), 30 );
?>

Note: This function counts words, not characters. It automatically handles HTML tags to prevent broken layouts. The third optional parameter lets you customize the 'more' text (default is '…').

Method 2: Using the PHP Function mb_strimwidth()

For precise character-based truncation, use PHP's mb_strimwidth() function.

<?php
// Trim the title to 30 characters (width)
echo mb_strimwidth(get_the_title(), 0, 30, "...");
?>

Note: This function counts by character width, which is better for mixed-language content. Ensure your server has the mbstring extension enabled. It does not handle HTML tags and may cut them off.

Method 3: Using a Custom Function

You can create a custom function for more control. Add this to your theme's functions.php file:

// Function to trim post title by character count
function custom_title_limit($limit) {
    $title = get_the_title();
    if (mb_strlen($title, 'UTF-8') > $limit) {
        $title = mb_substr($title, 0, $limit, 'UTF-8') . '...';
    }
    echo $title;
}

Then, call it in your template files (e.g., index.php, archive.php):

<?php custom_title_limit(30); ?>

Note: This custom function uses multi-byte string functions (mb_strlen, mb_substr) to correctly count characters in languages like Chinese. It does not handle HTML tags.

Summary & Recommendations

  • For most cases: Use wp_trim_words(). It's WordPress-native, safe with HTML, and counts by words.
  • For precise character limits: Use mb_strimwidth() or a custom function, but be aware they may break HTML tags in the content.

Post a Comment

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