fetch_feed: retrieve entries in the appearing order, not chronologically

I’m using WP function fetch_feed to retrieve a feed and display its items.

    <?php
    /* include the required file */     include_once(ABSPATH . WPINC . '/feed.php');
    /* specify the source feed   */     $rss = fetch_feed('FEED_URL');
    /* checks obj. is created    */     if (!is_wp_error( $rss ) ) :
    /* specify number of items   */     $maxitems = $rss->get_item_quantity(4);
    /* create an array of items  */     $rss_items = $rss->get_items(0, $maxitems);
endif;
    ?>
    <ul>
        <?php if ($maxitems == 0) echo '<li>Content not available.</li>';
    else
        // Loop through each feed item and display each item as a hyperlink.
        foreach ( $rss_items as $item ) : ?>
            <li>
                <a href="<?php echo $item->get_permalink(); ?>" title="<?php echo esc_html( $item->get_title() ); ?>" rel="external"><?php echo esc_html( $item->get_title() ); ?></a>
            </li>
            <?php endforeach; ?>
    </ul>

If I visit the feed in question with (e.g.) Firefox, I see the entries in the XML appearing order. fetch_feed retrieves the most recent instead (according to their “published” tag). How can I make sure it retrieves items according to their order on the XML feed (not chronologically).
Maybe is possible to set the order with this..?

Read More

EDIT: I tried adding $feed->enable_order_by_date(false); but it seems to break the function..

Related posts

Leave a Reply

1 comment

  1. Ok, found. I spent hours on this but I managed to find the solution.
    The command I was looking for was $rss->enable_order_by_date(false);.

    So you should set (for benefit of the community):

        <?php
        /* include the required file */     include_once(ABSPATH . WPINC . '/feed.php');
        /* specify the source feed   */     $rss = fetch_feed('FEED_URL');
        /* disable order by date     */     $rss->enable_order_by_date(false);
        /* checks obj. is created    */     if (!is_wp_error( $rss ) ) :
        /* specify number of items   */     $maxitems = $rss->get_item_quantity(X);
        /* create an array of items  */     $rss_items = $rss->get_items(0, $maxitems);
    endif;
        ?>
        <ul>
            <?php if ($maxitems == 0) echo '<li>Content not available.</li>';
        else
            // Loop through each feed item and display each item as a hyperlink.
            foreach ( $rss_items as $item ) : ?>
                <li>
                    <a href="<?php echo $item->get_permalink(); ?>" title="<?php echo esc_html( $item->get_title() ); ?>" rel="external"><?php echo esc_html( $item->get_title() ); ?></a>
                </li>
                <?php endforeach; ?>
        </ul>
    

    Hope this helps! 🙂