0

I'm using this script in two places on the same page to output some RSS feeds:

<?php
    include_once(ABSPATH . WPINC . '/feed.php');
    $rss = fetch_feed('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=BarackObama');
    $maxitems = $rss->get_item_quantity(3);
    $rss_items = $rss->get_items(0, $maxitems);
?>
<?php if ($maxitems == 0) echo '<p class="alert">No activity to display.</p>'; ?>
<ul>
<?php
    if (!$maxitems == 0)
    foreach ( $rss_items as $item ) : ?>
        <li>
            <a href="<?php echo $item->get_permalink(); ?>">
                <?php echo $item->get_title(); ?>
                <time datetime="<?php echo $item->get_local_date('%Y-%m-%d %H:%M'); ?>" class="timestamp">
                    <?php echo $item->get_local_date('%A %d %b %H:%M'); ?>
                </time>
            </a>
        </li>
    <?php endforeach; ?>
</ul>

I'm manually setting the cache lifetime in my functions.php to two hours:

function filter_handler( $seconds ) {
    return 7200;
}
add_filter( 'wp_feed_cache_transient_lifetime', 'filter_handler' );

A few times a day, the feed breaks and displays this error instead:

Fatal error: Call to undefined method WP_Error::get_item_quantity() in /public_html/wp-content/themes/twentyeleven/home-page.php on line 100

It seems WordPress' fetch of this Twitter feed occasionally fails, then the error is output for 2 hours until the cache is flushed.

How can I get around this?

1

This happens, because Twitter stopped the API v1. To get around WP_Error in your code:

// functions.php
function fetch_twitter()
{
    $rss = fetch_feed('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=BarackObama');

    if ( is_wp_error( $rss ) )
        return;

    // continue in your function
    $maxitems = $rss->get_item_quantity(3);
}

// template
fetch_twitter();

Won’t help much in your case. Switch to the new API.

  • Difficult to test since the problem is intermittent. It's been happening for a while now, be surprised if Twitter's API is that flakey. Thanks for the code to handle the error, have included that. – AlecRust Jun 6 '13 at 21:26
  • Unfortunately this still blocks the rest of the page from rendering when there's an error. Any way to prevent this? – AlecRust Jun 13 '13 at 0:16
  • Wrap it in a function. I will make an update. – fuxia Jun 13 '13 at 7:00
  • Thanks. Am I correct in assuming this won't work with API v1.1, since https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=BarackObama returns an error due to not being authenticated via OAuth? – AlecRust Jun 13 '13 at 17:13
  • @AlecRust Yes, seems so. – fuxia Jun 13 '13 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.