WordPress 自定义侧边栏部件
想在博客的侧边栏显示随机文章,使用了“中文 WordPress 工具箱”插件,功能介绍里说是可以显示随机文章的,但是这个插件比较老了,不支持 widget,便想到了改造一下这个插件。查了一下部件的语法。其语法如下:
- <?php
- function widget_mywidget($args) {
- extract($args);
- ?>
- <?php echo $before_widget; ?>
- <?php echo $before_title . 'My Widget' . $after_title; ?>
- My Widget
- <?php echo $after_widget; ?>
- <?php
- }
- register_sidebar_widget('My Widget', 'widget_mywidget');
- ?>
register_sidebar_widget 注册函数之后,输出部件标题 "My Widget" 及內容 "My Widget"。
又从 WordPress Widgets 文档中知道:不能在插件导入之后执行任何代码,要使用 plugins_loaded 这个 hook,所以 add_action 的对象即是 plugins_loaded。
最后,在插件程序文件 mulberrykit.php 后增加了如下代码:
- function widget_random_posts_init() {
- if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') )
- return;
- function random_posts_sidebar_module($args) {
- extract($args);
- echo $before_widget . $before_title . $title . $after_title;
- echo "<h2>随机文章</h2><ul>";
- random_posts();
- echo "</ul>";
- echo $after_widget;
- }
- register_sidebar_widget('Random Posts module', 'random_posts_sidebar_module');
- }
- add_action('plugins_loaded', 'widget_random_posts_init');
在管理后台的 外观 -> Widgets 中就可以找到 Random Posts module 这个部件了。