本文实例讲述了WordPress小工具制作方法。分享给大家供大家参考,具体如下:
WordPress是一个拥有着无与伦比拓展性的软件,它的侧边栏小工具很是方便。但是默认的那几个小工具完全不够用,或者说样式根本根本不能满足需要。今天就讲解一下如何制作一个小工具,然后接下来再给出一个评论小工具的制作实例。
小工具有三个部分,后台显示、数据保存、前台显示。当然如果你的小工具不需要在后台设置什么数据,那数据保存可以省掉了。一般来讲,一个小工具至少应该有这三个部分。
小工具是一个类,像侧边栏一样,你还得用代码注册它,它在能在后台使用。
代码如下:
//定义小工具类PostViewsclass PostViews extends WP_Widget{function PostViews(){//这是定义小工具信息的函数,也是类的构建函数}function form($instance){//这是表单函数,也就是控制后台显示的}function update($new_instance,$old_instance){//这是更新数据函数,小工具如果有设置选项,就需要保存更新数据}function widget($args,$instance){//这是控制小工具前台显示的函数}}function PostViews(){//注册小工具register_widget('PostViews');}//widges_init,小工具初始化的时候执行PostViews函数,add_action('widgets_init','PostViews');根据代码可知道,主要是继承WordPress的WP_Widget类,并且重载里面的函数,以此来达到自定义小工具的目的。
附:近期评论工具制作
WordPress其实自带有一个近期评论的小工具,但是那个只有显示谁在哪篇文章上面评论了,非常难看,根本不能满足我们的需要。这次来说明的小工具可以显示用户头像,评论内容,已经时间等各方面有用的信息。
还是和前面一样,继承 WP_Widget_Recent_Comments 类,代码:
代码如下:
/*** 继承WP_Widget_Recent_Comments* 这样就只需要重写widget方法就可以了*/class My_Widget_Recent_Comments extends WP_Widget_Recent_Comments {/*** 构造方法,主要是定义小工具的名称,介绍*/function My_Widget_Recent_Comments() {$widget_ops = array('classname' => 'widget_recent_comment', 'description' => __('显示最新评论内容'));$this->WP_Widget('my-recent-comments', __('我的最新评论', 'my'), $widget_ops);}/*** 小工具的渲染方法,这里就是输出评论*/function widget($args, $instance) {global $wpdb, $comments, $comment;$title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Comments') : $instance['title'], $instance, $this->id_base);if (empty($instance['number']) || !$number = absint($instance['number']))$number = 5;//获取评论,过滤掉管理员自己$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE user_id !=2 and comment_approved = '1' and comment_type not in ('pingback','trackback') ORDER BY comment_date_gmt DESC LIMIT $number");$output .= $before_widget;if ($title)$output .= $before_title . $title . $after_title;if ($comments) {// Prime cache for associated posts. (Prime post term cache if we need it for permalinks.)$post_ids = array_unique(wp_list_pluck($comments, 'comment_post_ID'));_prime_post_caches($post_ids, strpos(get_option('permalink_structure'), '%category%'), false);foreach ((array) $comments as $comment) {//头像$avatar = get_avatar($comment, 40);//作者名称$author = get_comment_author();//评论内容$content = apply_filters('get_comment_text', $comment->comment_content);$content = convert_smilies($content);//评论的文章$post = '' . get_the_title($comment->comment_post_ID) . '';//这里就是输出的html,可以根据需要自行修改$output .= ''}}$output .= $after_widget;echo $output;$cache[$args['widget_id']] = $output;wp_cache_set('my_widget_recent_comments', $cache, 'widget');}}完了之后还要注册小工具,这样就可以在后台拖动了
代码如下:
//注册小工具register_widget('My_Widget_Recent_Comments');希望本文所述对大家基于wordpress的程序设计有所帮助。














发表评论