How to set character limit on the_content() and th

2020-02-02 06:51发布

How do I set a character limit on the_content() and the_excerpt() in wordpress? I have only found solutions for the word limit - I want to be able to set an exact amount characters of outputted.

标签: php wordpress
9条回答
闹够了就滚
2楼-- · 2020-02-02 07:30

Replace <?php the_content();?> by the code below

<?php
$char_limit = 100; //character limit
$content = $post->post_content; //contents saved in a variable
echo substr(strip_tags($content), 0, $char_limit);
?>

php substr() function refrence

php strip_tags() function refrence

查看更多
相关推荐>>
3楼-- · 2020-02-02 07:31

just to help, if any one want to limit post length at home page .. then can use below code to do that..

the below code is simply a modification of @bfred.it Sir

add_filter("the_content", "break_text");

function limit_text($text){

  if(is_front_page())
  {
    $length = 250;
    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) . "... <a href='".get_permalink()."'>read more</a>";
  }else{
    return $text;
  }

}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-02 07:32

This also balances HTML tags so that they won't be left open and doesn't break words.

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) . " […]";
} 
查看更多
登录 后发表回答