A function to fetch blog content via rss feed

First things first, avoid defining functions inside functions. PHP doesn’t have a problem with it, but it’s usually a sign you’re “doing it wrong” and it just leads to unnecessary headaches.

Second, your foreach loop at the bottom is a little malformed. You need to define the <ul> outside the loop, and then append to $html – otherwise you just end up with the last item!

function wpse_187819_get_feed_html( $url ) {
    if ( is_wp_error( $rss = fetch_feed( $url ) ) )
        return; // Bail

    $maxitems  = $rss->get_item_quantity( 2 );
    $rss_items = $rss->get_items( 0, $maxitems );

    $html="<ul class="rss-items" id="wow-feed">";

    if ( $maxitems ) {
        foreach ( $rss_items as $item ) {
            $title = esc_attr( $item->get_title() );
            $link  = esc_url( $item->get_permalink() );

            $html .= '<li class="item">'; 
                if ( preg_match( '/<img.+?src="https://wordpress.stackexchange.com/questions/187819/(.+?)"https://wordpress.stackexchange.com/", $item->get_content(), $matches ) )
                    $html .= '<span class="rss-image"><img src="' . $matches[1] . '"/></span>';

                $html .= '<span class="data"><h5><a href="' . $link . '" title="' . $title . '"' . $title . '</a></h5></span>';
            $html .= '</li>';
        }

    } else {
        $html .= '<li>No items</li>';
    }

    // All done, now close the <ul>
    $html .= '</ul>';

    return $html;
}

Leave a Comment