玩WordPress » 实用插件 » 2008 » 10 » 10 » 让WordPress支持发表带有代码的文章

让WordPress支持发表带有代码的文章

WordPress发表带有代码的文章时,你会发觉文章中的代码会变得残缺不全甚至消失不见。不用担心,你的数据仍旧保存在数据库里,但由于WordPress在输出文章时要经过安全过滤,而代码基本都含有不适合直接显示为HTML的字符,这就导致了上述情况的发生。(是的,当你使用WYSIWYG编辑器时不会有这样的问题,但你这时是不能把代码作为一个“块”来进行修饰等动作的,所以使用HTML编辑器编写带有代码的文章才是王道。)

这里我将编写一个插件,她的作用是在安全过滤之前把代码中的特殊字符经过实体化,使它们能安全地显示。

插件只需要一个函数

function tranCode($content){
  preg_match_all('|\s<code>(.*?)

\s|is’, $content, $output);
$i = count($output[1]);
for ($n=0;$n<$i;$n++){
$transformed = '

' . htmlspecialchars(trim($output[1][$n]), ENT_QUOTES) . '

';
$content = str_replace($output[0][$n], $transformed, $content);
}
return $content;
}
然后把这个函数添加到WordPress的过滤器中

add_filter('the_content', 'tranCode', 0);
add_filter('comment_text', 'tranCode', 0);  //这个过滤器使留言也能发代码

加点CSS让代码看起来更加炫

pre.code{
  -moz-border-radius-bottomleft:.5em;
  -moz-border-radius-bottomright:.5em;
  -moz-border-radius-topleft:.5em;
  -moz-border-radius-topright:.5em;
  width: 475px;
  background: #000;
  color: #CCC;
  _height: 35px;
  margin: 0px;
  font: 16px "Courier New", "Times New Roman", cursive;
  overflow-x:auto;
  text-overflow: auto;
  word-break:keep-all;
  word-wrap:normal;
}
code{padding: 10px;display:block;}

效果看上面的代码吧。
我已经将这个插件打包好了,需要的童鞋可以下载安装,trancode.zip

如果你对上面的显示效果不满意,你要的是像编程软件中的代码高亮效果
WordPress代码高亮插件
可以看看这些插件->WordPress Plugins Extend

4 Responses to “让WordPress支持发表带有代码的文章”

  1. [...] 对&ltcode>code&lt/code>进行了过滤; [...]

  2. [...] 对<code>code</code>进行了过滤; [...]

  3. 雪深 says:

    很强大了 不过考虑自己不用经常插入代码 所以暂不采纳

Leave a Reply

gravatar