A
A
Andrey2018-03-14 10:29:45
WordPress
Andrey, 2018-03-14 10:29:45

Minimum excerpt text crop length in wordpress?

There is some custom code that cuts the_excerpt() to the first dot.

function strpos_arr($haystack, $needle) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false)  $pos_arr[] = $pos;
    }
    return is_array($pos_arr) ? min($pos_arr) : $pos;
}
add_filter(
  'the_excerpt',
  function ($excerpt) {
    return substr($excerpt,0,strpos_arr($excerpt,array('.', '?'))+1);
  }
);

The problem is that if the first period is too early, for example, the sentence consists of one word, then it looks somehow not very good. Please tell me how to add the ability to set the minimum number of characters before the first dot to this code. Those. if the first point is earlier than the specified number of characters, then the text is cut off at the second point.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2018-03-14
@azerphoenix

Hello!
To limit the length of an excerpt, I use the following code:

function get_excerpt($limit, $source = null){

    if($source == "content" ? ($excerpt = get_the_content()) : ($excerpt = get_the_excerpt()));
    $excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
    $excerpt = strip_shortcodes($excerpt);
    $excerpt = strip_tags($excerpt);
    $excerpt = substr($excerpt, 0, $limit);
    $excerpt = substr($excerpt, 0, strripos($excerpt, " "));
    $excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
    $excerpt = $excerpt.' ...';
    return $excerpt;
}

Maybe it will help you....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question