WordPressのプラグイン内で外部サイトのページをリクエストする場合は、wp_remote_get()、wp_remote_post()、wp_remote_head()などが便利。
※これらの関数は、wp-includes/http.php内で定義されている。
例えば、前記事の「WordPress.ORGからプラグインのダウンロード数を取得するPHPスクリプト」のコードをwp_remote_get()を使って書きなおすと、次のようになる。
<?php /** Author: redcocker Update: redcocker 2012/2/17 **/ function stat_count() { // Setting $address = 'プラグインページのURL'; $stat_count = -1; $response_data = wp_remote_get($address); if (is_wp_error($response_data) || $response_data['response']['code'] !== 200) { return $stat_count; } $stat_count = get_stat_count($response_data['body']); return $stat_count; } function get_stat_count($data) { preg_match("@<strong>Downloads: </strong>(.*?)<br />@", $data, $matches); $str = str_replace(',','',$matches[1]); settype($str, 'integer'); return number_format($str); } ?>
レスポンスがエラーだったり200以外の場合は、つまりは、想定したURLでページが見つからなかった場合は、-1を返す。
転送されているケースは考慮していないが、移転先もヘッダーから取得できそうな気が。