wordpress加入运行代码功能完美版
运行代码功能估计需要的人不多,但是博客写前端代码的人应该就需要,因为能够预览代码这样子体验非常好。
运行代码功能预览:
代码预览
网上有很多这样子的例子。但是基本上都是错误的,反正我没要找到正确的。
主要原因就是wordpress会自动添加分段标签p,br等等,导致代码不能够预览。
相信大家都对这个wordpress自动机制感到很绝望。
下面我们来看看怎么来做。
一、首先准备JS代码:
function runCode(objid) {
var winname = window.open('', "_blank", '');
var obj = document.getElementById(objid);
winname.document.open('text/html', 'replace');
winname.opener = null;
winname.document.write(obj.value);
winname.document.close();
}
function selectCode(objid){
var obj = document.getElementById(objid);
obj.select();
}
二、PHP代码:
function to_run_code ($attrs,$content='') {
extract(shortcode_atts(array(
'id' => 'runcode'
), $attrs));
if(empty($content)) return;
else {
return '
';
}
}
add_shortcode('runcode', 'to_run_code');
上面的代码就是我说的网上的大多数办法,这样子没法逃避wordpress的自动过滤机制,如果代码预览中js存在html标签,那么运行代码将失效。
经过我多次研究,写了一个自动替换的短代码方案,这个实在后期进行匹配过滤的。完全可以所见所得。
// 新版新窗口预览源码开始
$RunCode = new RunCode();
add_filter('the_content', array(&$RunCode, 'part_one'), -500);
add_filter('the_content', array(&$RunCode, 'part_two'), 500);
unset($RunCode);
class RunCode
{
var $blocks = array();
function part_one($content)
{
$str_pattern = "/(\< -runcode(.*?)\>(.*?)\< \/-runcode\>)/is";
if (preg_match_all($str_pattern, $content, $matches)) {
for ($i = 0; $i < count($matches[0]); $i++) {
$code = htmlspecialchars($matches[3][$i]);
$code = preg_replace("/(\s*?\r?\n\s*?)+/", "\n", $code);
$num = rand(1000,9999);
$id = "runcode_$num";
$blockID = "++RUNCODE_BLOCK_$num++";
$innertext='
代码预览
';
$this->blocks[$blockID] = $innertext;
$content = str_replace($matches[0][$i], $blockID, $content);
}
}
return $content;
}
function part_two($content)
{
if (count($this->blocks)) {
$content = str_replace(array_keys($this->blocks), array_values($this->blocks), $content);
$this->blocks = array();
}
return $content;
}
}
// 新版新窗口预览源码结束
注:这里的runcode前面的-是我加起以免被运行用的。
三、最后就是样式了:
.runcode{
width: 550px;
height: 150px;
font-size: 10pt;
padding: 10px;
background-color: #EEEEEE;
margin-bottom: 5px;
border-radius: 5px;
min-width: 625px;
max-width: 625px;}
四、使用方法:
编辑文章时,切换到html模式,输入类似代码:
< -runcode id="r1"> < -/runcode>
注:这里的runcode前面的-是我加起以免被运行用的。
输入的是runcode而不是-runcode。
要记住id不要相同了啊。
其余的wordpress会给你自动生成。
大家可以在我博客里进行测试。
WordPress短代码shortcode介绍 移除WordPress中的短代码shortcode的方法
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.