日志存档:02, 2008

WordPress 自定义侧边栏部件

2008-02-29,星期五 | 分类:PHP, WordPress | 标签: | 2,341 Views

想在博客的侧边栏显示随机文章,使用了“中文 WordPress 工具箱”插件,功能介绍里说是可以显示随机文章的,但是这个插件比较老了,不支持 widget,便想到了改造一下这个插件。查了一下部件的语法。其语法如下:

  1. <?php
  2. function widget_mywidget($args) { 
  3. extract($args);
  4. ?>
  5. <?php echo $before_widget; ?>
  6. <?php echo $before_title . 'My Widget' . $after_title; ?>
  7. My Widget
  8. <?php echo $after_widget; ?>
  9. <?php
  10. }
  11. register_sidebar_widget('My Widget', 'widget_mywidget');
  12. ?>

register_sidebar_widget 注册函数之后,输出部件标题 "My Widget" 及內容 "My Widget"。
又从 WordPress Widgets 文档中知道:不能在插件导入之后执行任何代码,要使用 plugins_loaded 这个 hook,所以 add_action 的对象即是 plugins_loaded。

最后,在插件程序文件 mulberrykit.php 后增加了如下代码:

  1. function widget_random_posts_init() {
  2.  
  3.   if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') )
  4.     return;
  5.  
  6.   function random_posts_sidebar_module($args) {
  7.     extract($args);
  8.  
  9.     echo $before_widget . $before_title . $title . $after_title;
  10.     echo "<h2>随机文章</h2><ul>";
  11.       random_posts();
  12.     echo "</ul>";
  13.     echo $after_widget;
  14.   }
  15.  
  16.   register_sidebar_widget('Random Posts module', 'random_posts_sidebar_module');
  17. }
  18.  
  19. add_action('plugins_loaded', 'widget_random_posts_init');

在管理后台的 外观 -> Widgets 中就可以找到 Random Posts module 这个部件了。