wordpress 不使用插件 实现 页面静态化


原文链接:http://www.51ask.org/article/366

 

 

wordpress 不使用插件 实现 页面静态化

 
 
 
功能:
首次访问页面会生成静态页面,可以设定生成静态文件时间,超过指定时间重新生成。
 
修改项目入口文件 index.php( 提前备份):
 
function is_mobile(){

		$regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
		$regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
		$regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";    
		$regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
		$regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
		$regex_match.=")/i";        
		return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));

	}

    $requestUri = '';
    if (isset($_SERVER['REQUEST_URI'])) { #$_SERVER["REQUEST_URI"] 只有 apache 才支持,
        $requestUri = $_SERVER['REQUEST_URI'];
    } else {
        if (isset($_SERVER['argv'])) {
            $requestUri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
        } else if(isset($_SERVER['QUERY_STRING'])) {
            $requestUri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
        }
    }
    $scheme = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = strstr(strtolower($_SERVER["SERVER_PROTOCOL"]), "/",true) . $scheme;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
    # 获取的完整url
    $_fullUrl = $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $requestUri;
		
	$staticDir = 'static/';

	if(is_mobile()) {
		$suffix = 'mobile';
	} else {
		$suffix = 'pc';
	}
	$fileDir = $staticDir.md5($_fullUrl).'_'.$suffix.'.html';

	//如果生成静态文件在1小时内,直接使用静态文件,否重新生成
	
	if (file_exists ( $fileDir ) && time () - filectime ( $fileDir ) < 3600) {

		include $fileDir;
	} else {
		ob_start ();
		if(file_exists ( $fileDir ))unlink($fileDir);
		define ( 'WP_USE_THEMES', true );
		/**
		 * Loads the WordPress Environment and Template
		 */
		require (dirname ( __FILE__ ) . '/wp-blog-header.php');
		$html = ob_get_contents ();
		$path = $fileDir;
		$fp = fopen($path,"w+");
		flock($fp, LOCK_EX) ;
		fwrite($fp,$html);
		flock($fp, LOCK_UN);
		fclose($fp);
	}

猜你喜欢

转载自51ask.iteye.com/blog/2370007
今日推荐