this is a RSS-question: Im pulling an RSS feed from a site to display on my homepage. It displays the titles correctly, but I want to truncate the number of characters per post so it doenst take up a long section if the title is long. How do I do that? here is the code Im using
<?php // Get RSS Feed(s) include_once(ABSPATH . WPINC . '/feed.php'); $rss = fetch_feed('http://examplesite.com/rss'); if (!is_wp_error( $rss ) ) : $maxitems = $rss->get_item_quantity(5); $rss_items = $rss->get_items(0, $maxitems); endif; ?> <ul> <?php if ($maxitems == 0) echo '<li>No items.</li>'; else foreach ( $rss_items as $item ) : ?> <li> <a href='<?php echo $item->get_permalink(); ?>' title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'> <?php echo $item->get_title(); ?></a> </li> <?php endforeach; ?> </ul> well I am trying to limit the number of words displayed in the excerpt Basicly, the problem is that I want to use the same excerpt in two different loops. The first one will display the whole excerpt, the second loop will only display a smaller part of it. Therefore I cannot limit the words number of ALL the excerpts, but I would need to do that locally. Ideally, if there is a solution to this I can use the same excerpts in many different places on the blog, using the same excerpt but in its longer/shorter version depending on the situation.
<?php $little_excerpt = substr(the_excerpt(),0,XY); ?> doesn’t work because the_excerpt() is not at string.
well we can Use get_the_excerpt() instead, that will do the trick. However, this is still limiting characters, not words.
I just found a solution to limiting the number of words in the excerpt without plugins. Put the following piece of code in your templates functions.php file:
<?php function string_limit_words($string, $word_limit) { $words = explode(' ', $string, ($word_limit + 1)); if(count($words) > $word_limit) array_pop($words); return implode(' ', $words); } ?> Next, put the following piece of code in your template where you want to display the excerpt:
<?php $excerpt = get_the_excerpt(); echo string_limit_words($excerpt,25); ?> Where 25 is the number of words to display.