WordPress教程

添加数量和排序选项到WordPress标签云小工具

阿里云

在上一篇文章《添加设置选项到 WordPress 原有的小工具中》中,我们介绍了如何添加自定义选项到原有小工具中。文本,倡萌将实例演示添加数量和排序选项到 WordPress 标签云小工具,所以,确保你先看下之前教程。

通过钩子全局修改标签云小工具的参数

其实,如果只是简单修改下标签云小工具的选项,我们可以直接通过 widget_tag_cloud_args 过滤器钩子来操作,具体代码示例如下:

也想出现在这里?联系我们
创客主机
  1. //custom widget tag cloud
  2. add_filter( 'widget_tag_cloud_args', 'theme_tag_cloud_args' );
  3. function theme_tag_cloud_args( $args ){
  4. 	$newargs = array(
  5. 		'smallest'    => 8,  //最小字号
  6. 		'largest'     => 22, //最大字号
  7. 		'unit'        => 'pt',   //字号单位,可以是pt、px、em或%
  8. 		'number'      => 45,     //显示个数
  9. 		'format'      => 'flat',//列表格式,可以是flat、list或array
  10. 		'separator'   => "\n",   //分隔每一项的分隔符
  11. 		'orderby'     => 'name',//排序字段,可以是name或count
  12. 		'order'       => 'ASC', //升序或降序,ASC或DESC
  13. 		'exclude'     => null,   //结果中排除某些标签
  14. 		'include'     => null,  //结果中只包含这些标签
  15. 		'link'        => 'view', //taxonomy链接,view或edit
  16. 		'taxonomy'    => 'post_tag', //调用哪些分类法作为标签云
  17. 	);
  18. 	$return = array_merge( $args, $newargs);
  19. 	return $return;
  20. }

第 5-16 行的代码就是各个参数的设置,根据需要修改即可,将全部代码添加到主题的 functions.php 或插件中即可。

添加选项到 WordPress 标签云小工具

好了,现在开始我们文本的话题,添加数量和排序选项到 WordPress 标签云小工具。WordPress 自带的标签云小工具的设置选项是非常简单的:

我们先来看下标签云小工具的注册代码:

  1. <?php
  2. /**
  3.  * Widget API: WP_Widget_Tag_Cloud class
  4.  *
  5.  * @package WordPress
  6.  * @subpackage Widgets
  7.  * @since 4.4.0
  8.  */
  9.  
  10. /**
  11.  * Core class used to implement a Tag cloud widget.
  12.  *
  13.  * @since 2.8.0
  14.  *
  15.  * @see WP_Widget
  16.  */
  17. class WP_Widget_Tag_Cloud extends WP_Widget {
  18.  
  19. 	/**
  20. 	 * Sets up a new Tag Cloud widget instance.
  21. 	 *
  22. 	 * @since 2.8.0
  23. 	 */
  24. 	public function __construct() {
  25. 		$widget_ops = array(
  26. 			'description'                 => __( 'A cloud of your most used tags.' ),
  27. 			'customize_selective_refresh' => true,
  28. 		);
  29. 		parent::__construct( 'tag_cloud', __( 'Tag Cloud' ), $widget_ops );
  30. 	}
  31.  
  32. 	/**
  33. 	 * Outputs the content for the current Tag Cloud widget instance.
  34. 	 *
  35. 	 * @since 2.8.0
  36. 	 *
  37. 	 * @param array $args     Display arguments including 'before_title', 'after_title',
  38. 	 *                        'before_widget', and 'after_widget'.
  39. 	 * @param array $instance Settings for the current Tag Cloud widget instance.
  40. 	 */
  41. 	public function widget( $args, $instance ) {
  42. 		$current_taxonomy = $this->_get_current_taxonomy( $instance );
  43.  
  44. 		if ( ! empty( $instance['title'] ) ) {
  45. 			$title = $instance['title'];
  46. 		} else {
  47. 			if ( 'post_tag' === $current_taxonomy ) {
  48. 				$title = __( 'Tags' );
  49. 			} else {
  50. 				$tax   = get_taxonomy( $current_taxonomy );
  51. 				$title = $tax->labels->name;
  52. 			}
  53. 		}
  54.  
  55. 		$show_count = ! empty( $instance['count'] );
  56.  
  57. 		$tag_cloud = wp_tag_cloud(
  58. 			/**
  59. 			 * Filters the taxonomy used in the Tag Cloud widget.
  60. 			 *
  61. 			 * @since 2.8.0
  62. 			 * @since 3.0.0 Added taxonomy drop-down.
  63. 			 * @since 4.9.0 Added the `$instance` parameter.
  64. 			 *
  65. 			 * @see wp_tag_cloud()
  66. 			 *
  67. 			 * @param array $args     Args used for the tag cloud widget.
  68. 			 * @param array $instance Array of settings for the current widget.
  69. 			 */
  70. 			apply_filters(
  71. 				'widget_tag_cloud_args',
  72. 				array(
  73. 					'taxonomy'   => $current_taxonomy,
  74. 					'echo'       => false,
  75. 					'show_count' => $show_count,
  76. 				),
  77. 				$instance
  78. 			)
  79. 		);
  80.  
  81. 		if ( empty( $tag_cloud ) ) {
  82. 			return;
  83. 		}
  84.  
  85. 		/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
  86. 		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
  87.  
  88. 		echo $args['before_widget'];
  89. 		if ( $title ) {
  90. 			echo $args['before_title'] . $title . $args['after_title'];
  91. 		}
  92.  
  93. 		echo '<div class="tagcloud">';
  94.  
  95. 		echo $tag_cloud;
  96.  
  97. 		echo "</div>\n";
  98. 		echo $args['after_widget'];
  99. 	}
  100.  
  101. 	/**
  102. 	 * Handles updating settings for the current Tag Cloud widget instance.
  103. 	 *
  104. 	 * @since 2.8.0
  105. 	 *
  106. 	 * @param array $new_instance New settings for this instance as input by the user via
  107. 	 *                            WP_Widget::form().
  108. 	 * @param array $old_instance Old settings for this instance.
  109. 	 * @return array Settings to save or bool false to cancel saving.
  110. 	 */
  111. 	public function update( $new_instance, $old_instance ) {
  112. 		$instance             = array();
  113. 		$instance['title']    = sanitize_text_field( $new_instance['title'] );
  114. 		$instance['count']    = ! empty( $new_instance['count'] ) ? 1 : 0;
  115. 		$instance['taxonomy'] = stripslashes( $new_instance['taxonomy'] );
  116. 		return $instance;
  117. 	}
  118.  
  119. 	/**
  120. 	 * Outputs the Tag Cloud widget settings form.
  121. 	 *
  122. 	 * @since 2.8.0
  123. 	 *
  124. 	 * @param array $instance Current settings.
  125. 	 */
  126. 	public function form( $instance ) {
  127. 		$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
  128. 		$count = isset( $instance['count'] ) ? (bool) $instance['count'] : false;
  129. 		?>
  130. 		<p>
  131. 			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
  132. 			<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
  133. 		</p>
  134. 		<?php
  135. 		$taxonomies       = get_taxonomies( array( 'show_tagcloud' => true ), 'object' );
  136. 		$current_taxonomy = $this->_get_current_taxonomy( $instance );
  137.  
  138. 		switch ( count( $taxonomies ) ) {
  139.  
  140. 			// No tag cloud supporting taxonomies found, display error message.
  141. 			case 0:
  142. 				?>
  143. 				<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="" />
  144. 				<p>
  145. 					<?php _e( 'The tag cloud will not be displayed since there are no taxonomies that support the tag cloud widget.' ); ?>
  146. 				</p>
  147. 				<?php
  148. 				break;
  149.  
  150. 			// Just a single tag cloud supporting taxonomy found, no need to display a select.
  151. 			case 1:
  152. 				$keys     = array_keys( $taxonomies );
  153. 				$taxonomy = reset( $keys );
  154. 				?>
  155. 				<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="<?php echo esc_attr( $taxonomy ); ?>" />
  156. 				<?php
  157. 				break;
  158.  
  159. 			// More than one tag cloud supporting taxonomy found, display a select.
  160. 			default:
  161. 				?>
  162. 				<p>
  163. 					<label for="<?php echo $this->get_field_id( 'taxonomy' ); ?>"><?php _e( 'Taxonomy:' ); ?></label>
  164. 					<select class="widefat" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>">
  165. 					<?php foreach ( $taxonomies as $taxonomy => $tax ) : ?>
  166. 						<option value="<?php echo esc_attr( $taxonomy ); ?>" <?php selected( $taxonomy, $current_taxonomy ); ?>>
  167. 							<?php echo esc_html( $tax->labels->name ); ?>
  168. 						</option>
  169. 					<?php endforeach; ?>
  170. 					</select>
  171. 				</p>
  172. 				<?php
  173. 		}
  174.  
  175. 		if ( count( $taxonomies ) > 0 ) {
  176. 			?>
  177. 			<p>
  178. 				<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" <?php checked( $count, true ); ?> />
  179. 				<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show tag counts' ); ?></label>
  180. 			</p>
  181. 			<?php
  182. 		}
  183. 	}
  184.  
  185. 	/**
  186. 	 * Retrieves the taxonomy for the current Tag cloud widget instance.
  187. 	 *
  188. 	 * @since 4.4.0
  189. 	 *
  190. 	 * @param array $instance Current settings.
  191. 	 * @return string Name of the current taxonomy if set, otherwise 'post_tag'.
  192. 	 */
  193. 	public function _get_current_taxonomy( $instance ) {
  194. 		if ( ! empty( $instance['taxonomy'] ) && taxonomy_exists( $instance['taxonomy'] ) ) {
  195. 			return $instance['taxonomy'];
  196. 		}
  197.  
  198. 		return 'post_tag';
  199. 	}
  200. }

以上代码位于 wp-includes/widgets/class-wp-widget-tag-cloud.php 文件中。我们将 57-79 行的代码抽出来看一下:

  1. 	$tag_cloud = wp_tag_cloud(
  2. 			/**
  3. 			 * Filters the taxonomy used in the Tag Cloud widget.
  4. 			 *
  5. 			 * @since 2.8.0
  6. 			 * @since 3.0.0 Added taxonomy drop-down.
  7. 			 * @since 4.9.0 Added the `$instance` parameter.
  8. 			 *
  9. 			 * @see wp_tag_cloud()
  10. 			 *
  11. 			 * @param array $args     Args used for the tag cloud widget.
  12. 			 * @param array $instance Array of settings for the current widget.
  13. 			 */
  14. 			apply_filters(
  15. 				'widget_tag_cloud_args',
  16. 				array(
  17. 					'taxonomy'   => $current_taxonomy,
  18. 					'echo'       => false,
  19. 					'show_count' => $show_count,
  20. 				),
  21. 				$instance
  22. 			)
  23. 		);

代码中有一个函数 wp_tag_cloud() 用于输出标签云的内容,它里面包含了几个参数,并且有一个 widget_tag_cloud_args 过滤器钩子,这就是上文【通过钩子全局修改标签云小工具的参数】所展示的钩子和所有可用参数。

添加设置选项到标签云小工具

  1. /**
  2.  * 添加新选项到标签云小工具
  3.  * @param  [type] $widget   [description]
  4.  * @param  [type] $return   [description]
  5.  * @param  [type] $instance [description]
  6.  * @return [type]           [description]
  7.  */
  8. function cmhello_tag_cloud_new_options( $widget, $return, $instance ) {
  9.  
  10.     // Are we dealing with a tag_cloud widget?
  11.     if ( 'tag_cloud' == $widget->id_base ) {
  12.  
  13.         ?>
  14.             <p>
  15.                 <label for="<?php echo $widget->get_field_id('tags_number'); ?>"><?php _e( '显示数量:', 'textdomain' ); ?></label>
  16.                 <input type="text" class="widefat" id="<?php echo $widget->get_field_id('tags_number'); ?>" name="<?php echo $widget->get_field_name('tags_number'); ?>" value="<?php if (isset ( $instance['tags_number']) && $instance['tags_number']) echo esc_attr( $instance['tags_number'] ); ?>" />
  17.             </p>
  18.             <p>
  19.                 <label for="<?php echo $widget->get_field_id('orderbytag'); ?>"><?php _e('排序依据:', 'textdomain' ) ?></label>
  20.                 <select  class="widefat" id="<?php echo $widget->get_field_id('orderbytag'); ?>" name="<?php echo $widget->get_field_name('orderbytag'); ?>">
  21.                     <option <?php if ( isset($instance['orderbytag']) && $instance['orderbytag'] == 'name') echo 'selected="SELECTED"'; else echo ''; ?>  value="name"><?php  echo __('名称','textdomain');?></option>
  22.                     <option <?php if ( isset($instance['orderbytag']) && $instance['orderbytag'] == 'count') echo 'selected="SELECTED"'; else echo ''; ?> value="count"><?php echo __('数量','textdomain');?></option>
  23.                 </select>
  24.             </p>
  25.             <p>
  26.                 <label for="<?php echo $widget->get_field_id('ordertag'); ?>"><?php _e('排序方式:', 'textdomain' ) ?></label>
  27.                 <select  class="widefat" id="<?php echo $widget->get_field_id('ordertag'); ?>" name="<?php echo $widget->get_field_name('ordertag'); ?>">
  28.                     <option <?php if ( isset($instance['ordertag']) && $instance['ordertag'] == 'ASC') echo 'selected="SELECTED"'; else echo ''; ?>  value="ASC"><?php  echo __('升序','textdomain');?></option>
  29.                     <option <?php if ( isset($instance['ordertag']) && $instance['ordertag'] == 'DESC') echo 'selected="SELECTED"'; else echo ''; ?> value="DESC"><?php echo __('降序','textdomain');?></option>
  30.                     <option <?php if ( isset($instance['ordertag']) && $instance['ordertag'] == 'RAND') echo 'selected="SELECTED"'; else echo ''; ?> value="RAND"><?php echo __('随机','textdomain');?></option>
  31.                 </select>
  32.             </p>
  33.         <?php
  34.     }
  35. }
  36. add_filter('in_widget_form', 'cmhello_tag_cloud_new_options', 10, 3 );

我们通过 in_widget_form 过滤钩子,并在第 11 行'tag_cloud' == $widget->id_base 确保新选项只适用于标签云小工具,这样我们就可以在标签云小工具中看到新的选项了:

保存标签云新选项的值

  1. /**
  2.  * 更新标签云新字段的值
  3.  */
  4. function cmhello_tag_cloud_instance($instance, $new_instance, $old_instance) {
  5.     $instance['tags_number'] = stripslashes($new_instance['tags_number']);
  6.     $instance['ordertag'] = stripslashes($new_instance['ordertag']);
  7.     $instance['orderbytag'] = stripslashes($new_instance['orderbytag']);
  8.     return $instance;
  9. }
  10. add_filter('widget_update_callback', 'cmhello_tag_cloud_instance', 10, 3);

通过 widget_update_callback 钩子,让小工具保存的时候,可以更新我们新增的选项设置。

修改标签云的输出

我们的新选项已经添加并可以保存,下面我们就需要将我们的新选项的值应用到标签云的参数中:

  1. /**
  2.  * 通过钩子去修改标签云的参数
  3.  * @param  [type] $args     [description]
  4.  * @param  [type] $instance [description]
  5.  * @return [type]           [description]
  6.  */
  7. function cmhello_tag_cloud_args( $args, $instance){
  8.     if(isset($instance['tags_number'])){
  9.         $args['number'] = $instance['tags_number']; //Limit number of tags
  10.     }
  11.     if(isset($instance['orderbytag'])){
  12.         $args['orderby'] = $instance['orderbytag'];
  13.     }
  14.     if(isset($instance['ordertag'])){
  15.         $args['order'] = $instance['ordertag'];
  16.     }
  17.     return $args;
  18. }
  19. add_filter('widget_tag_cloud_args', 'cmhello_tag_cloud_args', 10, 2);

前文我们已经提到了 widget_tag_cloud_args 钩子,所以我们可以将新的选项通过钩子应用到标签云函数 wp_tag_cloud() 中,达到我们的目的。

完整的示例代码

以下就是我们最终用到的所有代码:

  1. /**
  2.  * 添加新选项到标签云小工具
  3.  * @param  [type] $widget   [description]
  4.  * @param  [type] $return   [description]
  5.  * @param  [type] $instance [description]
  6.  * @return [type]           [description]
  7.  */
  8. function cmhello_tag_cloud_new_options( $widget, $return, $instance ) {
  9.  
  10.     // Are we dealing with a tag_cloud widget?
  11.     if ( 'tag_cloud' == $widget->id_base ) {
  12.  
  13.         ?>
  14.             <p>
  15.                 <label for="<?php echo $widget->get_field_id('tags_number'); ?>"><?php _e( '显示数量:', 'textdomain' ); ?></label>
  16.                 <input type="text" class="widefat" id="<?php echo $widget->get_field_id('tags_number'); ?>" name="<?php echo $widget->get_field_name('tags_number'); ?>" value="<?php if (isset ( $instance['tags_number']) && $instance['tags_number']) echo esc_attr( $instance['tags_number'] ); ?>" />
  17.             </p>
  18.             <p>
  19.                 <label for="<?php echo $widget->get_field_id('orderbytag'); ?>"><?php _e('排序依据:', 'textdomain' ) ?></label>
  20.                 <select  class="widefat" id="<?php echo $widget->get_field_id('orderbytag'); ?>" name="<?php echo $widget->get_field_name('orderbytag'); ?>">
  21.                     <option <?php if ( isset($instance['orderbytag']) && $instance['orderbytag'] == 'name') echo 'selected="SELECTED"'; else echo ''; ?>  value="name"><?php  echo __('名称','textdomain');?></option>
  22.                     <option <?php if ( isset($instance['orderbytag']) && $instance['orderbytag'] == 'count') echo 'selected="SELECTED"'; else echo ''; ?> value="count"><?php echo __('数量','textdomain');?></option>
  23.                 </select>
  24.             </p>
  25.             <p>
  26.                 <label for="<?php echo $widget->get_field_id('ordertag'); ?>"><?php _e('排序方式:', 'textdomain' ) ?></label>
  27.                 <select  class="widefat" id="<?php echo $widget->get_field_id('ordertag'); ?>" name="<?php echo $widget->get_field_name('ordertag'); ?>">
  28.                     <option <?php if ( isset($instance['ordertag']) && $instance['ordertag'] == 'ASC') echo 'selected="SELECTED"'; else echo ''; ?>  value="ASC"><?php  echo __('升序','textdomain');?></option>
  29.                     <option <?php if ( isset($instance['ordertag']) && $instance['ordertag'] == 'DESC') echo 'selected="SELECTED"'; else echo ''; ?> value="DESC"><?php echo __('降序','textdomain');?></option>
  30.                     <option <?php if ( isset($instance['ordertag']) && $instance['ordertag'] == 'RAND') echo 'selected="SELECTED"'; else echo ''; ?> value="RAND"><?php echo __('随机','textdomain');?></option>
  31.                 </select>
  32.             </p>
  33.         <?php
  34.     }
  35. }
  36. add_filter('in_widget_form', 'cmhello_tag_cloud_new_options', 10, 3 );
  37.  
  38. /**
  39.  * 更新标签云新字段的值
  40.  */
  41. function cmhello_tag_cloud_instance($instance, $new_instance, $old_instance) {
  42.     $instance['tags_number'] = stripslashes($new_instance['tags_number']);
  43.     $instance['ordertag'] = stripslashes($new_instance['ordertag']);
  44.     $instance['orderbytag'] = stripslashes($new_instance['orderbytag']);
  45.     return $instance;
  46. }
  47. add_filter('widget_update_callback', 'cmhello_tag_cloud_instance', 10, 3);
  48.  
  49. /**
  50.  * 通过钩子去修改标签云的参数
  51.  * @param  [type] $args     [description]
  52.  * @param  [type] $instance [description]
  53.  * @return [type]           [description]
  54.  */
  55. function cmhello_tag_cloud_args( $args, $instance){
  56.     if(isset($instance['tags_number'])){
  57.         $args['number'] = $instance['tags_number']; //Limit number of tags
  58.     }
  59.     if(isset($instance['orderbytag'])){
  60.         $args['orderby'] = $instance['orderbytag'];
  61.     }
  62.     if(isset($instance['ordertag'])){
  63.         $args['order'] = $instance['ordertag'];
  64.     }
  65.     return $args;
  66. }
  67. add_filter('widget_tag_cloud_args', 'cmhello_tag_cloud_args', 10, 2);

总结

本文提到的两种修改标签云参数的方式:

通过钩子直接修改参数:直接方便,但是不灵活,比如不同地方无法输出不同数量的标签云,也无法修改排序等

添加新选项:开发有点难(但我们已提供代码),非常灵活,每个标签云小工具都可以单独设置选项

熟悉开发的朋友可能会说,我们可以直接注销掉原有的标签云小工具,重新注册自己的,的确,这也是一种实现方式。

添加数量和排序选项到 WordPress 标签云小工具

已有 261 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!