在WordPress中创建自定义小工具非常简单,只需要遵循以下步骤:
class My_Custom_Widget extends WP_Widget {
}
class My_Custom_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'my_custom_widget',
__('My Custom Widget', 'my_custom_widget_domain'),
array('description' => __('Displays recent posts', 'my_custom_widget_domain'))
);
}
public function widget($args, $instance) {
$title = apply_filters('widget_title', $instance['title']);
$num_posts = apply_filters('widget_num_posts', $instance['num_posts']);
echo $args['before_widget'];
if(!empty($title)) {
echo $args['before_title'] . $title . $args['after_title'];
}
$recent_posts = wp_get_recent_posts(array(
'numberposts' => $num_posts,
'post_status' => 'publish'
));
echo '<ul>';
foreach($recent_posts as $post) {
echo '<li><a href="' . get_permalink($post['ID']) . '">' . $post['post_title'] . '</a></li>';
}
echo '</ul>' . $args['after_widget'];
}
}
function my_custom_widget_load() {
register_widget('My_Custom_Widget');
}
add_action('widgets_init', 'my_custom_widget_load');
这将使自定义小工具出现在WordPress小工具页面中。
示例代码:https://gist.github.com/skippednote/3055cfab45f65abc90395e4dfbe98368