Going to start this blog off with a simple coding problem that was presented to me earlier today. Kaus (Cheryle) over at the PokerAffiliateListings.com forums asked for help with displaying a wordpress feed using simplepie on a static html page.
A Little Background
Cheryle is using wordpress to power the news section of her website but she wants to display the posts on the static portion of her site. She is accomplishing this by grabbing the feed from wordpress and parsing it using simplepie. The full feed that is available from her website contains “img” tags which she also wants to parse but she does not want to show the full content, only a brief description.
SimplePie contains two different functions for displaying the main portion of a feed:
echo $item->get_content();
?>
and
echo $item->get_description();
?>
The first example displays the full content of the feed while the second example displays a brief description.
The Problem
Using $item->get_description(); does not parse the “img” tags the way she would like. In fact, it completely removes them. In addition to that, she would like to be able to control the amount of content that is being displayed for asthetical purposes.
Mike’s SimplePie – Simple Solution
By creating a snippet of code, we can truncate the $item->get_content(); function to display only the required number of words. Here is the code:
$content = $item->get_content();
$numwords = 40;
preg_match("/([\S]+\s*){0,$numwords}/", $content, $desc);
$shortdesc = trim($desc[0]);
echo $shortdesc;
?>
{ 2 comments… read them below or add one }
Thanks Mike for the help…thought of something that may help people later on..Is there a way to do it where you can truncate the number of characters or words?
Thank you for this piece of code. It was exactly the solution I just needed.