因为想要在文章中插入一些动态的内容来做一些前端的demo,自然用到了JavaScript和CSS,目前我用的wordpress2.9对插入JavaScript的功能已经支持得蛮好,即使使用富文本编辑器和HTML视图切换的时候JavaScript不会被过滤掉,但是用link标签还是会被过滤。 

网上有个per post css的wordpress插件,利用的是自定义meta域的方法,在页面渲染的时候插入css的link,虽然我没搞过WP的插件开发,但是代码倒也挺容易看懂,基本上不用解释了。 

下面这个插件,性能不好,如果文章和css比较多的,每次查看的时候都要做很多次无效的循环(比如单独查看每个页面的时候),所以我没有选择这个插件。我换了个思路解决不能插入link标签的问题。 


<?php

/*
Plugin Name: Per-Post CSS
Version: 1.1
Plugin URI: <a href="http://trevorcreech.com/geekery/wordpress/per-post-css/">http://trevorcreech.com/geekery/wordpress/per-post-css/</a>
Description: This plugin allows you to specify a chunk of CSS, which will be included in the header only when viewing that post, or a page where that post appears.  Put the custom CSS in a Custom Field called "Per-Post CSS".  The Custom Fields interface can be found directly below the file upload interface when you are creating or editing a post.
Author: Trevor Creech
Author URI: <a href="http://trevorcreech.com">http://trevorcreech.com</a>
*/

function ppc_header()
{
 global $posts;
 for($i=0;$i<count($posts);$i++)
 {
  $ppc_embed = get_post_meta($posts[$i]->ID, 'Per-Post CSS', false);
  $ppc_ext = get_post_meta($posts[$i]->ID, 'Per-Post CSS File', false);
  for($j=0;$j<count($ppc_embed);$j++)
  {
   $ppc_output .=  '/* Embedded CSS for "' . $posts[$i]->post_title . "\" */\n";
   $ppc_output .= $ppc_embed[$j] . "\n";
  }
  for($j=0;$j<count($ppc_ext);$j++)
  {
   $ppc_output .=  '/* Externel CSS for "' . $posts[$i]->post_title . "\" */\n";
   $ppc_output .= "@import url(\"$ppc_ext[$j]\")" . "\n";
  }
 }
 if($ppc_output)
 {
  echo "<style type=\"text/css\">\n/* Per-Post CSS */\n";
  echo $ppc_output;
      }
 echo "</style>\n";
}

add_action('wp_head', 'ppc_header');
?>

我的解决办法是既然JavaScript标签现在wordpress已经有支持了,那么就用JavaScript为需要单独使用css的文章或者页面加载css文件,下面的代码摘录自我的一个测试页面: 

 
<script src="http://www.google.com/jsapi"></script>

<script type="text/javascript">// <![CDATA[
    google.load("jquery", "1.3.2");
// ]]&gt;</script>

<script src="http://www.haojii.com/webdev/working-with-events/events.js" type="text/javascript"></script>
<script src="http://www.haojii.com/webdev/working-with-events/loadcss.js" type="text/javascript"></script>

 

//loadcss.js
$(document).ready(function() {
   var $per_post_css = $('<link href="http://www.haojii.com/webdev/working-with-events/working-with-events-part-1.css" media="screen, projection" rel="stylesheet" type="text/css"></link>');
   $(document.body).append($per_post_css);
});