How to set character limit on the_content() and the_excerpt() in wordpress

后端 未结 9 1330
臣服心动
臣服心动 2020-12-07 23:36

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 cha

相关标签:
9条回答
  • 2020-12-07 23:59

    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

    0 讨论(0)
  • 2020-12-08 00:03

    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) . " […]";
    } 
    
    0 讨论(0)
  • 2020-12-08 00:03

    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;
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题