如何在wordpress中设置the_content()和the_excerpt()的字符限制

Tho*_*mas 20 php wordpress

如何在wordpress中的the_content()和the_excerpt()上设置字符限制?我只找到了字限制的解决方案 - 我希望能够设置输出的确切数量字符.

ric*_*age 29

您可以使用Wordpress过滤器回调函数.在主题目录中,创建一个名为的文件functions.php并添加以下内容:

<?php   
  add_filter("the_content", "plugin_myContentFilter");

  function plugin_myContentFilter($content)
  {
    // Take the existing content and return a subset of it
    return substr($content, 0, 300);
  }
?>
Run Code Online (Sandbox Code Playgroud)

plugin_myContentFilter()每次请求帖子/页面的内容时,都会调用该函数the_content()- 它为您提供内容作为输入,并将使用您从函数返回的任何内容作为后续输出或其他过滤器函数.

您也可以为the_exercpt()- add_filter()然后使用一个函数作为回调.

有关更多详细信息,请参阅Wordpress过滤器参考文档.

  • 注意,你最终可能会打开标签.有一些过滤器会阻止它,但我不记得它的名字. (4认同)
  • 找到它,最终,它是[balanceTags()](http://codex.wordpress.org/Function_Reference/balanceTags) (3认同)

Rve*_*urt 25

甚至更简单,无需创建过滤器:使用PHP mb_strimwidth将字符串截断为特定宽度(长度).只需确保使用其中一种get_语法.例如内容:

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>
Run Code Online (Sandbox Code Playgroud)

这将把字符串剪切为400个字符并用它关闭....只需通过指向固定链接,在末尾添加"阅读更多"链接get_permalink().

<a href="<?php the_permalink() ?>">Read more </a>
Run Code Online (Sandbox Code Playgroud)

当然你也可以read more在第一行建立.不仅仅是替换'...''<a href="' . get_permalink() . '">[Read more]</a>'

  • 应该注意的是,如果存在任何HTML字符,它可能会破坏布局,因为标签可能没有关闭标签. (4认同)

fre*_*nte 17

这也可以平衡HTML标记,这样它们就不会打开并且不会破坏单词.

add_filter("the_content", "break_text");
function break_text($text){
    $length = 500;
    if(strlen($text)<$length+10) return $text;//don't cut if too short

    $break_pos = strpos($text, ' ', $length);//find next space after desired length
    $visible = substr($text, 0, $break_pos);
    return balanceTags($visible) . " […]";
} 
Run Code Online (Sandbox Code Playgroud)


Pur*_*iya 10

wp_trim_words 此功能将文本修剪为一定数量的单词并返回修剪后的文本.

例:-

echo wp_trim_words( get_the_content(), 40, '...' );
Run Code Online (Sandbox Code Playgroud)