网上针对WordPress 运行代码的插件和非插件版的方法都已经过时了,最主要的问题还是加入运行框中的代码会自动插入换行符,这直接导致了代码无法运行。下面这个方法完美解决的这些问题。
加入functions.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>代码预览</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;
}
}
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();
}
参考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>
希望textarea高度自适应而不出现滚动条
网上有css方法,没有效果,故采用jquery方法实现
$(function() {
$('.main-content textarea').autoHeight();
});
$.fn.extend({
autoHeight: function(){
return this.each(function(){
var $this = $(this);
if( !$this.attr('_initAdjustHeight') ){
$this.attr('_initAdjustHeight', $this.outerHeight());
}
_adjustH(this).on('input', function(){
_adjustH(this);
});
});
//重置高度
function _adjustH(elem){
var $obj = $(elem);
return $obj.css({height: $obj.attr('_initAdjustHeight'), 'overflow-y': 'hidden'}).height( elem.scrollHeight );
}
}
});
WordPress插件
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
