基於H. Maor的代碼示例,這裏是我用我的插件功能:
/**
* Check if an item exists out there in the "ether".
*
* @param string $url - preferably a fully qualified URL
* @return boolean - true if it is out there somewhere
*/
function webItemExists($url) {
if (($url == '') || ($url == null)) { return false; }
$response = wp_remote_head($url, array('timeout' => 5));
$accepted_status_codes = array(200, 301, 302);
if (! is_wp_error($response) && in_array(wp_remote_retrieve_response_code($response), $accepted_status_codes)) {
return true;
}
return false;
}
我我已經在輔助類中做了這個方法,但是將它放在主題的functions.php文件中應該使它在任何地方都可以訪問。但是,你應該總是寫在課堂上並實例化它們。隔離你的插件和主題功能要好得多。
有了這個地方,你可以簡單地使用:
如果(webItemExists( 'http://myurl.com/thing.png')){打印 '它iexists'; }
大多數情況下,您將使用WordPress調用通過相對或完全限定的URL訪問所有項目。如果您具有相對於/uploads/2012/12/myimage.png之類的內容的引用,只需添加get_site_url()即可將其轉換爲完全限定的URL與WordPress相對URL。調用webItemExists函數時的$ string。
的可能重複(http://stackoverflow.com/questions/981954/how -can-one-check-see-if-a-remote-file-exists-using-php) - 用於文件使用['is_file'](http://php.net/is_file)。 – hakre