0

I want my posts to be limited to number characters. I want this to happen on the page that shows all my posts. I am using this snippet. The read more link also appears when you are viewing the single post. I only want this to happen on the multi post view

enter image description here enter image description here

//for index.php that calls content
    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) . "<a href='".get_permalink()."'>read more</a> ";
}
0

The normal way to do this would be to use the_excerpt() instead of the_content() in your archive templates, then use this filter the change the number of words that appear in the excerpt:

function wpse_280633_excerpt_length() {
    return 20;
}
add_filter( 'excerpt_length', 'wpse_280633_excerpt_length' );

If you want to stick with what you've got and not apply it to single post views, use a combination of is_main_query() and is_singular() to check if you're in a list of posts or not:

function wpse_280633_break_text( $content ) {
    if ( is_main_query() && ! is_singular() ) {
        $length = 500;
        if(strlen($content)<$length+10) return $content;//don't cut if too short

        $break_pos = strpos($content, ' ', $length);//find next space after desired length
        $visible = substr($content, 0, $break_pos);
        $content = balanceTags($visible) . "<a href='".get_permalink()."'>read more</a> ";
    }

    return $content;
}
add_filter( 'the_content', 'wpse_280633_break_text' );
  • that worked for the single post view. but now the thumbnail image and excerpt are not showing on the post collection view... I didnt think it would be that hard to limit the amount of characters on a post collections view. are there any other ways? – Sebastian Alidad Sep 21 '17 at 5:35
  • Sorry I didn't replace every instance of $text with $content. I've updated my answer. But the only reason images would be missing is if the image was part of the content. If you added it as a featured image it wouldn't be affected by the the_content filter. You should be using my first method though, it's the simplest way to do it. You're making it harder on yourself. – Jacob Peattie Sep 21 '17 at 5:43
0

You can restrict the length of character in following way

<?php 
   $str= get_the_excerpt();
   echo $str1= substr ($str,0,50);
?> 

Please check this and let me know if you are facing any issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.