Matthew Sims
Matthew Sims

Reputation: 25

Wordpress shortcode only returning 1 from feed despite using foreach

I am trying to create a custom Wordpress plugin which utilises shortcodes to output what I want. In this text code I am attempting to read an rss file and spit out just a list of the top 5 feeds.

The $showno is one of the shortcode variables so I can use the following [player show=foo snowno=5]. In the example code $show isn't used.

The code below only shows the most recent item in the feed list. If I change the return to echo then it works as expected except it show at the top of the post instead of where I've entered the shortcode. I searched for an answer to this and the solution offered was simply "use return" which I've done...

Appreciate advice. Thanks

include_once(ABSPATH . WPINC . '/rss.php');         

$num_items = $showno;
$feedurl = 'http://feeds.bbci.co.uk/news/rss.xml';
$feed = fetch_rss($feedurl);
$items = array_slice ($feed->items, 0, $num_items); 

foreach ($items as $item ) {
  $title = $item[title];
  $mp3link   = $item[link];
  $description  =  $item[description];
  return "<li>$title - $description</li>";  
}     

Upvotes: 0

Views: 802

Answers (1)

brasofilo
brasofilo

Reputation: 26075

Shortcodes should be returned not echoed.

In your code, you are breaking the execution of the foreach and returning the first value.

You should build a string variable and after the foreach loop return it, so all your loop will be included, e.g.:

$final_html = '';
foreach( $items as $item )
{
    $final_html .= "<li>$title - $description</li>"; 
}
return $final_html;

Upvotes: 1

Related Questions