Twitter feed – Failed to open stream [closed]

How to do remote requests in WordPress: Use the appropriate API

First, there’s the WP HTTP API, which should be used for such tasks. And second, one should never ever use the @ operator, as this one suppresses error messages or notices and will successfully lock you out from troubleshooting your bugs. Just because you can’t see it, doesn’t mean that it’s not there.

How to use the API

The first thing to do is make the actual request:

// Example
$api_url  = https://api.twitter.com/1/users/show.json?screen_name=SOME_USER_NAME';
$response = wp_remote_get( $api_url );

Then you check if you got an error and output it for debugging.

if ( is_wp_error( $response ) )
    return $response->get_error_message();

The headers can give you additional information. The same goes for the response code and the response message

$headers = wp_remote_retrieve_headers( $response );
$code    = wp_remote_retrieve_response_code( $response );
$message = wp_remote_retrieve_response_message( $response );

Of course most of the response code and message is a lie and just what the server answers. Remote APIs are – in my personal experience – mostly lousy coded and send 200/OK answers for errors as well.

Now that you got everything through, you finally just grab the result and do whatever you need to do with it:

$data = wp_remote_retrieve_body( $response );
// BE FANTASTIC HERE!

How to debug WP HTTP requests

The one who implemented this API originally, was clever enough to offer a hook at the end of a request, that gives you every detailed information that you can imagine. Just use it.

add_action( 'http_api_debug', 'wpse78251_http_api_debug', 10, 5 );
function wpse78251_http_api_debug( $response, $type, $class, $args, $url ) {
    var_dump( 'Request URL: ' . var_export( $url, true ) );
    var_dump( 'Request Args: ' . var_export( $args, true ) );
    var_dump( 'Request Response : ' . var_export( $response, true ) );
}

More info about debugging those requests can be found on this answer I gave.

Additional Information / Advanced and in-depth info

I wrote another answer about remote requests for this question, which also shows the basic concept of caching and parsing the response.