WordPress制作彩色标签云widget小工具的教程

标签云是博客和网站相对常见的网站元素。使用WordPress构建网站时,也可以使用标签云,但是传统的标签云文本是黑色的,看起来很普通,并不那么漂亮。那么有没有办法改变它呢?答案是肯定的,我们可以使用彩色标签云功能。下面教你如何做一个彩色标签云widget小工具:

模板主题目录下新建一个colortag-widget.php文件,把下面小工具代码放入colortag-widget.php。

<?php
class Color_Tag_Widget extends WP_Widget { //继承了 WP_Widget 这个类来创建新的小工具(Widget)
  function Color_Tag_Widget ()
  {
    $widget_ops = array('description' => '一个彩色标签云');
    $control_ops = array('width' => 400, 'height' => 300);
    parent::WP_Widget(false,$name='一个彩色标签云',$widget_ops,$control_ops);  
                //parent::直接使用父类中的方法
                //$name 这个小工具的名称,
                //$widget_ops 可以给小工具进行描述等等。
                //$control_ops 可以对小工具进行简单的样式定义等等。
  }
  function form($instance) { // 给小工具(widget) 添加表单内容
    $title = esc_attr($instance['title']);
    $tagnum = esc_attr($instance['tagnum']);
  ?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_attr_e('Title:'); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></label></p>
  <p><label for="<?php echo $this->get_field_id('tagnum'); ?>"><?php esc_attr_e('最多显示标签数:'); ?> <input class="widefat" id="<?php echo $this->get_field_id('tagnum'); ?>" name="<?php echo $this->get_field_name('tagnum'); ?>" type="text" value="<?php echo $tagnum; ?>" /></label></p>
  <?php
    }
  function update($new_instance, $old_instance) { // 更新保存
  $instance = $old_instance;
  $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
  $instance[ 'tagnum' ] = strip_tags( $new_instance[ 'tagnum' ] );
      return $instance;
  }
  function widget($args, $instance) { // 输出显示在页面上
  extract( $args );
        $title = apply_filters('widget_title', empty($instance['title']) ? __('彩色标签云') : $instance['title']);
    if ( ! $tagnum = absint( $instance['tagnum'] ) ) $tagnum = '16';//默认放置最多16个标签
        ?>
              <?php echo $before_widget; ?>
                  <?php if ( $title )
                        echo $before_title . $title . $after_title; ?>
                      <div class="colortags"><?php wp_tag_cloud('smallest=12&largest=18&unit=px&number='.$tagnum.'&orderby=count&order=DESC');?></div>
              <?php echo $after_widget; ?>

        <?php
  }
}
register_widget('Color_Tag_Widget');

?>

👋 感谢您的观看!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享