priktop
priktop

Reputation: 1155

Wordpress - Excerpt character alternative?

I'm totally new to WordPress so be easy :)

I the following code in a template:

<?php excerpt(20);?>

What this does is limit the text with 20 words. I am now wondering if there is some sort of similar function that limits by characters instead of words?

Thanks!

Upvotes: 0

Views: 1714

Answers (4)

Shobhit Chugh
Shobhit Chugh

Reputation: 180

Please use this code for limiting post content...

<a href="<?php the_permalink(); ?>"><?php substr($post->post_content, 0, xy); ?> ...</a>

Change the limit of XY....

Upvotes: 0

Shelly
Shelly

Reputation: 380

I use this:

add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
    return '500';
}

function better_excerpt($limit, $id = '') {
global $post;

if($id == '') $id = $post->ID;
else $id = $id;

$postinfo = get_post($id);
if($postinfo->post_excerpt != '')
  $post_excerpt = $postinfo->post_excerpt;
else 
  $post_excerpt = $postinfo->post_content;

$myexcerpt = explode(' ', $post_excerpt, $limit);
if (count($myexcerpt) >= $limit) {
  array_pop($myexcerpt);
  $myexcerpt = implode(' ',$myexcerpt).'...';
} else {
  $myexcerpt = implode(' ',$myexcerpt);
}   
$myexcerpt = preg_replace('`\[[^\]]*\]`','',$myexcerpt);
$stripimages = preg_replace('/<img[^>]+\>/i', '', $myexcerpt);
return $stripimages;
}

And then in my theme file, I just call it in with:

better_excerpt('50') //50 being how many words I want

Useful for custom plugins/widgets too.

Upvotes: 2

Mark
Mark

Reputation: 3271

Wordpress doesn't support the character delimiter for the excerpt method, there's a plugin called Advanced Excerpt that does. After installing you can call the_advanced_excerpt('length=20&use_words=0')

Upvotes: 1

Gavin
Gavin

Reputation: 2567

I use this in my functions.php:

function truncate ($str, $length=10, $trailing='...'){
    // take off chars for the trailing
    $length-=mb_strlen($trailing);
    if (mb_strlen($str)> $length){
        // string exceeded length, truncate and add trailing dots
        $str = mb_substr($str,0,$length);
        $str = explode('. ',$str);
        for( $i=0; $i<(sizeof($str)-2); $i++ ):
            $newstr .= $str[$i].". ";
        endfor;
        return $newstr;
    } else{
        // string was already short enough, return the string
        $res = $str;
    }
    return $res;
}

It should truncate to a character count, but then truncate back further to the last period before the truncation. It does get problematic when your excerpt includes links, however, or other markup - in other words, it's best to use the Excerpt field in the post rather than auto-excerpting with this function, because you can't use HTML in the excerpt field.

Upvotes: 1

Related Questions