DeveWork

制作WordPress“带Gravatar头像评论”小工具(集成主题中、含选项)

最近在进一步折腾WordPress 主题的开发,在侧边栏小工具那里想做一个可独立于主题的、类似插件的带头像评论小工具。通过WordPress 官方文档与一些资料大概了解了小工具制作的一些知识,但对于我等PHP 菜鸟,完全自己开发是不可能的;于是在网络上找到了一段代码,分享并备忘一下。

关于WordPress 中小工具的开发,除了WordPress官方文档外,有一篇“阿叔工作室”的文章也不错,点击查看。这里不多说了。

下面的代码得到的“带Gravatar头像评论”小工具可以集成到主题中,小工具后台拥有相关选项。代码是从系统自带的评论小工具中改进过来的,兼容性良好。代码作者:陈杰斌,感谢原作者。

 'my_widget_recent_comments', 'description' => __('显示最新评论内容'));
        $this->WP_Widget('my-recent-comments', __('我的最新评论', 'my'), $widget_ops);
    }

    /**
     * 小工具的渲染方法,这里就是输出评论
     */
    function widget($args, $instance) {
        global $wpdb, $comments, $comment;

        $cache = wp_cache_get('my_widget_recent_comments', 'widget');

        if (!is_array($cache))
            $cache = array();

        if (!isset($args['widget_id']))
            $args['widget_id'] = $this->id;

        if (isset($cache[$args['widget_id']])) {
            echo $cache[$args['widget_id']];
            return;
        }

        extract($args, EXTR_SKIP);
        $output = '';
        $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;

        $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');

在后台-外观-小工具 启用即可。

要修改的地方还挺多的,要熟悉CSS、html以及一些WordPress 函数。

一些相关文章:

制作WordPress侧边栏“随机文章”小工具并集成在主题中的方法

制作WordPress侧边栏“博客统计”小工具并集成在主题中的方法

制作WordPress侧边栏“热门文章”小工具并集成在主题中的方法