【WP教程】WordPress文章页添加运行测试代码功能

作者:晓白pos网 发布时间:2020-12-26 17:58:08

效果如下:
教程

第一步:将以下PHP代码添加至当前主题的
functions.php 文件中:

// 运行代码功能PHP脚本
$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?ns*?)+/", "n", $code);
                $num = rand(1000,9999);
                $id = "runcode_$num";
                $blockID = "<p>++RUNCODE_BLOCK_$num++";
                $innertext='<h3><span class="btn btn--secondary">代码预览:</span></h3><textarea id="'.$id.'" class="runcode" style="height: 100px;">'. $code . '</textarea><input class="btn btn--secondary" type="button" value="运行代码" onclick="runCode(''.$id.'')"/><input class="btn btn--secondary" style="margin-left: 30px;"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;
    }
}

第二步:以下JS代码添加至当前主题的 footer.php 文件中:

<script type="text/javascript">
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();
}
</script>

第三步:将以下CSS代码添加至当前主题的例外CSS或者头部风格CSS文件中:

.runcode{
  width: 100%;
  font-size:13px;
  padding:10px 15px;
  color:#eee;
  background-color: #263540;
  margin-bottom:5px;
  border-radius:2px;
  overflow:hidden; /* 删除此行表示可以滚动代码框 */
}

第四步:在撰写文章时,用文本模式输入以下标签,标签中填写需要运行的代码即可:

<runcode>这里填写需要运行的代码</runcode>

 

【WP教程】WordPress文章页添加运行测试代码功能
标签:, , , , ,

联系邮箱:ert5tyx@163.com(三个工作日内处理)
Copyright © 2020 · 晓白pos网 皖ICP备2022013394号-7