Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Right now I'm using the following code in my sidebar, which grabs the first term connected to a post from a taxonomy called "peoples" and displays it along with a link and description.

<?php $taxonomy = 'peoples';$terms = get_the_terms( $post->ID , 'peoples' );  if ( !empty( $terms ) ) : foreach ( $terms as $term ) {if($counter++ >= 1) break; $link = get_term_link( $term, $taxonomy ); if ( !is_wp_error( $link ) ) echo '<h2>Profile: ' . $term->name . '</h2><ul id="profile"><li class="big-listing ' . $term->slug. '"><div class="text">' .$term->description.'</div></li></ul>';} endif;?>

The problem is, my descriptions are ususally more than 400 words long, so I need to figure out how I can limit their length to, say, 40 words.

I've been searching for answer for a good three months now, lol; but I'm not having any luck. Does anyone have a function that can handle this?

Thanks

share|improve this question

1 Answer 1

up vote 0 down vote accepted
function trunc($phrase, $max_words, $after = null) {
    $phrase_array = explode(' ',$phrase);
    if(count($phrase_array) > $max_words && $max_words > 0)
        $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)) . $after;
    return $phrase;
}

This function returns the input shortened if there are more words in it than $max_words. You use it like this:

$string = "This is a sample string";
echo trunc($string, 3);

This will echo out "This is a"

In your case you have to use it like

<?php $taxonomy = 'peoples';$terms = get_the_terms( $post->ID , 'peoples' );  if ( !empty( $terms ) ) : foreach ( $terms as $term ) {if($counter++ >= 1) break; $link = get_term_link( $term, $taxonomy ); if ( !is_wp_error( $link ) ) echo '<h2>Profile: ' . $term->name . '</h2><ul id="profile"><li class="big-listing ' . $term->slug. '"><div class="text">' .trunc($term->description, 40).'</div></li></ul>';} endif;?>

The third parameter is for after the string if it's get shortened.

$string = "This is a sample string";
echo trunc($string, 3, '...');

This will echo out "This is a..."

share|improve this answer
    
Perfect! Thanks Rob :D –  Ahni Dec 23 '11 at 3:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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