wordpress加入运行代码功能完美版
运行代码功能估计需要的人不多,但是博客写前端代码的人应该就需要,因为能够预览代码这样子体验非常好。
运行代码功能预览:
代码预览
网上有很多这样子的例子。但是基本上都是错误的,反正我没要找到正确的。
主要原因就是wordpress会自动添加分段标签p,br等等,导致代码不能够预览。
相信大家都对这个wordpress自动机制感到很绝望。
下面我们来看看怎么来做。
一、首先准备JS代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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代码:
1 2 3 4 5 6 7 8 9 10 11 | function to_run_code ($attrs,$content='') { extract(shortcode_atts(array( 'id' => 'runcode' ), $attrs)); if(empty($content)) return; else { return '<textarea id="'.$id.'">'. $content . '</textarea> <br /> <input type="button" value="运行代码" data-runid="'.$id.'" onclick="toruncode(this)" />'; } } add_shortcode('runcode', 'to_run_code'); |
上面的代码就是我说的网上的大多数办法,这样子没法逃避wordpress的自动过滤机制,如果代码预览中js存在html标签,那么运行代码将失效。
经过我多次研究,写了一个自动替换的短代码方案,这个实在后期进行匹配过滤的。完全可以所见所得。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | // 新版新窗口预览源码开始 $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 = "<p>++RUNCODE_BLOCK_$num++"; $innertext='<h3>代码预览</h3><textarea id="'.$id.'" class="runcode">'. $code . '</textarea><input type="button" value="运行代码" onclick="runCode(\''.$id.'\')"/><input style="margin-left: 47px;"type="button" value="全选代码" onclick="selectCode(\''.$id.'\')"/>'; $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前面的-是我加起以免被运行用的。
三、最后就是样式了:
1 2 3 4 5 6 7 8 9 10 | .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模式,输入类似代码:
1 2 3 | < -runcode id="r1"> <script>alert("明凯博客测试短代码功能");</script> < -/runcode> |
注:这里的runcode前面的-是我加起以免被运行用的。
输入的是runcode而不是-runcode。
要记住id不要相同了啊。
其余的wordpress会给你自动生成。
大家可以在我博客里进行测试。
WordPress短代码shortcode介绍 移除WordPress中的短代码shortcode的方法