类文档

WP_Widget_Categories

💡 云策文档标注

概述

WP_Widget_Categories 是 WordPress 核心类,用于实现分类目录小部件,显示分类列表或下拉菜单。它继承自 WP_Widget,提供配置和输出功能。

关键要点

  • 继承自 WP_Widget,用于创建分类目录小部件,支持列表或下拉形式显示。
  • 包含四个核心方法:__construct() 初始化小部件,widget() 输出内容,update() 处理设置更新,form() 生成设置表单。
  • 支持自定义标题、显示文章数量、层级结构和下拉菜单选项,通过过滤器如 widget_categories_dropdown_args 可调整参数。

代码示例

// 示例:创建 WP_Widget_Categories 实例并注册小部件
add_action( 'widgets_init', function() {
    register_widget( 'WP_Widget_Categories' );
} );

注意事项

  • 使用 wp_dropdown_categories() 函数生成下拉菜单,需注意 HTML ID 的唯一性以避免冲突。
  • 设置更新时使用 sanitize_text_field() 清理标题输入,确保安全性。
  • 小部件支持自定义选择性刷新和 REST API 实例显示,需在构造时配置相关选项。

📄 原文内容

Core class used to implement a Categories widget.

Description

See also

Methods

Name Description
WP_Widget_Categories::__construct Sets up a new Categories widget instance.
WP_Widget_Categories::form Outputs the settings form for the Categories widget.
WP_Widget_Categories::update Handles updating settings for the current Categories widget instance.
WP_Widget_Categories::widget Outputs the content for the current Categories widget instance.

Source

class WP_Widget_Categories extends WP_Widget {

/**
* Sets up a new Categories widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'classname' => 'widget_categories',
'description' => __( 'A list or dropdown of categories.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'categories', __( 'Categories' ), $widget_ops );
}

/**
* Outputs the content for the current Categories widget instance.
*
* @since 2.8.0
* @since 4.2.0 Creates a unique HTML ID for the `<select>` element
* if more than one instance is displayed on the page.
*
* @param array $args Display arguments including 'before_title', 'after_title',
* 'before_widget', and 'after_widget'.
* @param array $instance Settings for the current Categories widget instance.
*/
public function widget( $args, $instance ) {
static $first_dropdown = true;

$default_title = __( 'Categories' );
$title = ! empty( $instance['title'] ) ? $instance['title'] : $default_title;

/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );

$count = ! empty( $instance['count'] ) ? '1' : '0';
$hierarchical = ! empty( $instance['hierarchical'] ) ? '1' : '0';
$dropdown = ! empty( $instance['dropdown'] ) ? '1' : '0';

echo $args['before_widget'];

if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}

$cat_args = array(
'orderby' => 'name',
'show_count' => $count,
'hierarchical' => $hierarchical,
);

if ( $dropdown ) {
printf( '<form action="%s" method="get">', esc_url( home_url() ) );
$dropdown_id = ( $first_dropdown ) ? 'cat' : "{$this->id_base}-dropdown-{$this->number}";
$first_dropdown = false;

echo '<label class="screen-reader-text" for="' . esc_attr( $dropdown_id ) . '">' . $title . '</label>';

$cat_args['show_option_none'] = __( 'Select Category' );
$cat_args['id'] = $dropdown_id;

/**
* Filters the arguments for the Categories widget drop-down.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_dropdown_categories()
*
* @param array $cat_args An array of Categories widget drop-down arguments.
* @param array $instance Array of settings for the current widget.
*/
wp_dropdown_categories( apply_filters( 'widget_categories_dropdown_args', $cat_args, $instance ) );

echo '</form>';

ob_start();
?>

<script>
( ( dropdownId ) => {
const dropdown = document.getElementById( dropdownId );
function onSelectChange() {
setTimeout( () => {
if ( 'escape' === dropdown.dataset.lastkey ) {
return;
}
if ( dropdown.value && parseInt( dropdown.value ) > 0 && dropdown instanceof HTMLSelectElement ) {
dropdown.parentElement.submit();
}
}, 250 );
}
function onKeyUp( event ) {
if ( 'Escape' === event.key ) {
dropdown.dataset.lastkey = 'escape';
} else {
delete dropdown.dataset.lastkey;
}
}
function onClick() {
delete dropdown.dataset.lastkey;
}
dropdown.addEventListener( 'keyup', onKeyUp );
dropdown.addEventListener( 'click', onClick );
dropdown.addEventListener( 'change', onSelectChange );
})( <?php echo wp_json_encode( $dropdown_id, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); ?> );
</script>

';
}
?>

<ul>

</ul>

';
}
}

echo $args['after_widget'];
}

/**
* Handles updating settings for the current Categories widget instance.
*
* @since 2.8.0
*
* @param array $new_instance New settings for this instance as input by the user via
* WP_Widget::form().
* @param array $old_instance Old settings for this instance.
* @return array Updated settings to save.
*/
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['count'] = ! empty( $new_instance['count'] ) ? 1 : 0;
$instance['hierarchical'] = ! empty( $new_instance['hierarchical'] ) ? 1 : 0;
$instance['dropdown'] = ! empty( $new_instance['dropdown'] ) ? 1 : 0;

return $instance;
}

/**
* Outputs the settings form for the Categories widget.
*
* @since 2.8.0
*
* @param array $instance Current settings.
*/
public function form( $instance ) {
// Defaults.
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$count = isset( $instance['count'] ) ? (bool) $instance['count'] : false;
$hierarchical = isset( $instance['hierarchical'] ) ? (bool) $instance['hierarchical'] : false;
$dropdown = isset( $instance['dropdown'] ) ? (bool) $instance['dropdown'] : false;
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" />
</p>

<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'dropdown' ); ?>" name="<?php echo $this->get_field_name( 'dropdown' ); ?>"<?php checked( $dropdown ); ?> />
<label for="<?php echo $this->get_field_id( 'dropdown' ); ?>"></label>
<br />

<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>"<?php checked( $count ); ?> />
<label for="<?php echo $this->get_field_id( 'count' ); ?>"></label>
<br />

<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'hierarchical' ); ?>" name="<?php echo $this->get_field_name( 'hierarchical' ); ?>"<?php checked( $hierarchical ); ?> />
<label for="<?php echo $this->get_field_id( 'hierarchical' ); ?>"></label>
</p>
</pre><p class="wporg-dot-link-list"><a href="https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-categories.php/">View all references</a> <a href="https://core.trac.wordpress.org/browser/tags/6.9.4/src/wp-includes/widgets/class-wp-widget-categories.php#L17">View on Trac</a> <a href="https://github.com/WordPress/wordpress-develop/blob/6.9.4/src/wp-includes/widgets/class-wp-widget-categories.php#L17-L222">View on GitHub</a></p></section>

<section class="wp-block-wporg-code-reference-related" data-nosnippet="true"><h2 id="related" class="is-toc-heading wp-block-heading has-heading-5-font-size" tabindex="-1" ><a href="#related">Related</a></h2> <section style="margin-top:var(--wp--preset--spacing--20)" class="wp-block-wporg-code-table" id="uses"><figure class="wp-block-table "><table><thead><tr><th scope="col">Uses</th><th scope="col">Description</th></tr></thead><tbody><tr class=""><td><a href="https://developer.wordpress.org/reference/classes/wp_widget/">WP_Widget</a><code>wp-includes/class-wp-widget.php

Core base class extended to register widgets.

Changelog

Version Description
2.8.0 Introduced.