AxureShop的演示地址因为加了框架和参数,URL变得异常的长。所以我想把他们变得短一些。然后就开始研究起自建短网址了。正好我们有一个axure.shop的域名,用来给axureshop做短网址正合适。
世面上开源的短网址系统不多,短网址这套东西是五六年前热门的东西。现在基本上没人做了。通过考古,发现YOURLS不错,多年前好像还用过。果断下载安装一个,打开一看,果然是上个时代的产物。不过功能倒是很完善,插件也很丰富,也提供了API接口。
接下来就是集成到WordPress上了,没有好使的插件,只能自己集成了。
函数short_the_url()是用来生成短网址的。可以用这个函数将任意URL转换成短网址。AxureShop里面是直接将演示地址那里加上这个函数即可。
后面的代码是将文章中的外链替换为短网址。
function short_the_url($the_url)
{
$api_url = 'https://axure.shop/yourls-api.php';
$timestamp = time();
$signature = md5( $timestamp . '此处为API秘钥' );
// Init the CURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_HEADER, 0); // No header in the result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
curl_setopt($ch, CURLOPT_POST, 1); // This is a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, array( // Data to POST
'url' => $the_url,
'format' => 'json',
'action' => 'shorturl',
'timestamp' => $timestamp,
'signature' =>$signature,
));
// Fetch and return content
$data = curl_exec($ch);
curl_close($ch);
// Do something with the result. Here, we echo the long URL
$data = json_decode( $data ,true);
return $data['shorturl'];
}
//给外部链接加上跳转
function git_go_url($content){
preg_match_all('/<a(.*?)href="(.*?)"(.*?)>/',$content,$matches);
if($matches && !is_page('about')){
foreach($matches[2] as $val){
if(strpos($val,'://')!==false && strpos($val,home_url())===false && !preg_match('/.(jpg|jepg|png|ico|bmp|gif|tiff)/i',$val)){
$content=str_replace("href="$val"", "href="".short_the_url($val).""",$content);
}
}
}
return $content;
}
add_filter('the_content', 'git_go_url');
下回我去也试试?