2015年4月24日星期五

Setting the wp_remote_get() User Agent

I was recently trying to make some API requests from within WordPress using `wp_remote_get()`, but the site I was asking for data from was rejecting requests from the default WordPress User Agent. I tried to set the user agent to something different, but it still wasn’t working:


$response = wp_remote_get($url, array(

  'timeout' => 20,

  'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:20.0) Gecko/20100101 Firefox/20.0'

));


Thankfully, Otto spotted my problem. The `user-agent` key needs to be lowercase so that it is picked up properly by the WordPress core code. This works:


$response = wp_remote_get($url, array(

  'timeout' => 20,

  'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:20.0) Gecko/20100101 Firefox/20.0'

));


And there you have it. It’s always nice to have an extra set of eyes on some code.

没有评论:

发表评论