WordPress函数wp_trim_words保持英文单词完整性用法

建站知识 2025年8月26日

在WordPress中,wp_trim_words函数用于截断字符串并限制单词数量。如果你希望在截断时保持单词的完整性(让单词显示全),可以通过自定义函数来实现。

以下是一个示例代码,展示如何修改你的代码以确保截断时显示完整的单词:

function custom_trim_content($content, $num_words = 360, $more = '') {
    $content = wp_strip_all_tags($content);
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]>', $content);

    // Split the content into words
    $words = explode(' ', $content);

    // Trim the content to the specified number of words
    $trimmed_content = array_slice($words, 0, $num_words);

    // Join the words back into a string
    $trimmed_content = implode(' ', $trimmed_content);

    // Check if the content was trimmed
    if (count($words) > $num_words) {
        $trimmed_content .= $more;
    }

    return $trimmed_content;
}

// Usage
$trimmed_content = custom_trim_content($post->post_content, 360, '');
echo $trimmed_content;

代码说明

wp_strip_all_tags和apply_filters:

wp_strip_all_tags用于移除HTML标签。

apply_filters用于应用WordPress的过滤器,确保内容经过所有必要的处理。

explode:

将内容按空格分割成单词数组。

array_slice:

截取数组中的前$num_words个单词。

implode:

将截取后的单词数组重新组合成字符串。

$more:

如果内容被截断,可以在末尾添加自定义的字符串,例如“…”。

使用方法

将上述代码添加到你的主题的functions.php文件中,然后在需要的地方调用custom_trim_content函数即可。

这样,你就可以确保在截断内容时不会截断单词,而是显示完整的单词。

相关文章