最近访客
libatt的头像-狐狸库
libatt
百度未收录

WordPress文章页添加运行代码测试功能

效果演示

WordPress文章页添加运行代码测试功能-狐狸库

第一步:

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

// <a href="https://www.902d.com/tag/172" title="【查看含有[运行]标签的文章】" target="_blank">运行</a>代码功能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?\n\s*?)+/", "\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>
温馨提示: 本文最后更新于2022/10/26 11:37:09。若文章内容或图片失效,请 留言联系站长反馈!
!
也想出现在这里? 联系我们
创意广告
© 版权声明
THE END
点赞0赞赏 分享
评论 抢沙发

请登录后发表评论

    请登录后查看评论内容