Search code examples
phparrayswordpressshortcodesplice

PHP array splice not working


I'm trying to build a shortcode in wp that displays data from 2 RSS feeds.

The problem is that I can't limit the number of items in array. I tried these solutions and none worked.

function rss_posts_func( $atts ){
    $feed = fetch_feed(array('rss-feed-1', 'rss-feed-2'));
    $feed = array();
    $feed = array_splice($feed, 0, 3);
    // Loop the results
     $content = '<ul class="rss-aggregator">';
    foreach($feed->get_items() as $item) {
        $content .= '<li class="feed-item">';
        $content .= '<a href='.$item->get_permalink().'>';
        $content .= $item->get_title();
        $content .= '</a></li>';
    }
    $content .= '</ul>';
    return $content;
}

Solution

  • Fixed with:

    function rss_posts_func( $atts ){
        $i = 1;
        $feed = fetch_feed(array('rss-feed-1', 'rss-feed-2'));
         $content = '<ul class="rss-aggregator">';
        foreach($feed->get_items() as $item) {
            $content .= '<li class="feed-item">';
            $content .= '<a href='.$item->get_permalink().'>';
            $content .= $item->get_title();
            $content .= '</a></li>';
            if($i++ == 8) break;
        }
        $content .= '</ul>';
        return $content;
    }