0

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

0
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..."

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.