0

I want to show several post excerpt, so I create function

function my_excerpt($limit) {
    $excerpt = explode(' ', get_the_excerpt(), $limit);
    if (count($excerpt)>=$limit) {
        array_pop($excerpt);
        $excerpt = implode(" ",$excerpt).'...';
    } else {
        $excerpt = implode(" ",$excerpt);
    }
    $excerpt = preg_replace('`[[^]]*]`','',$excerpt);
    return $excerpt;
}

and I use it:

<?php  echo bereza_excerpt(35); ?>

but I have problem - I cant save post formatting.

Is it possible to recreate this function and save text formatting in post excerpt?

1 Answer 1

0

One option would be to use substr in your function:

function my_excerpt($limit) {
    $excerpt = get_the_excerpt();
    if(strlen($excerpt) > $limit) {
        // trim to $limit characters
        $excerpt = substr($excerpt, 0, $limit);
        // remove any truncated words
        $excerpt = substr($excerpt, 0, strippos($excerpt, " "));
        $excerpt = trim(preg_replace('/\s+/', ' ', $excerpt));
    }
    return $excerpt;
}

Another way is to filter the excerpt, which will change the length of all your excerpts sitewide:

add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
    return 30;
}
1
  • what is "strippos" function?
    – name name2
    Commented Apr 6, 2017 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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