wordpress运行代码功能非插件完美版
以下代码由PHP站长网 52php.cn收集自互联网现在PHP站长网小编把它分享给大家,仅供参考 运行代码功能估计需要的人不多,但是博客写前端代码的人应该就需要,因为能够预览代码这样子体验非常好。网上针对 wordpress 运行代码的插件和非插件版的方法都已经过时了,最主要的问题还是加入运行框中的代码会自动插入换行符,这直接导致了代码无法运行。网上有很多这样子的例子。但是基本上都是错误的,反正我没要找到正确的,主要原因就是 wordpress 会自动添加分段标签 p,br 等等,导致代码不能够预览,相信大家都对这个 wordpress 自动机制感到很绝望,下面我们来看看怎么来做,下面这个方法完美解决的这些问题。 代码预览<script>alert("创客云运行代码测试功能");</script> 一、首先准备 JS 代码:JS 函数控制运行代码按钮和全选按钮。 //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(); } 二、functions 代码:网上的大多数办法,都没法逃避 wordpress 的自动过滤机制,如果代码预览中 js 存在 html 标签,那么运行代码将失效,经过我多次研究,写了一个自动替换的短代码方案,这个实在后期进行匹配过滤的,完全可以所见所得。 $RunCode = new RunCode(); add_filter('the_content',array(&$RunCode,'part_one'),-500); add_filter('the_content','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?ns*?)+/","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 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; } } 参考 CSS:.runcode{ width: 100%; font-size:13px; padding:10px 15px; color:#eee; background-color: #263540; margin-bottom:5px; border-radius:2px; overflow:hidden } 运行方法在撰写文章时切换到 html 模式,输入以下标签即可: <runcode>//这里贴要运行的代码</runcode> 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |