函数文档

the_widget()

💡 云策文档标注

概述

the_widget() 是一个 WordPress 模板标签函数,用于在主题模板中直接输出任意已注册的小部件。它允许开发者通过代码动态显示小部件,无需依赖侧边栏或小部件区域。

关键要点

  • 函数接受三个参数:$widget(小部件的 PHP 类名,必需)、$instance(小部件实例设置数组,可选,默认空数组)和 $args(配置小部件显示的参数数组,可选)。
  • $args 参数包括 before_widget、after_widget、before_title 和 after_title,用于自定义小部件输出的 HTML 包装。
  • 支持 WordPress 核心小部件,如 WP_Widget_Archives、WP_Widget_Categories 等,也支持自定义小部件类。
  • 使用前需确保小部件已通过 register_widget() 注册,否则会触发 _doing_it_wrong() 警告。
  • 函数内部应用了 widget_display_callback 过滤器,并触发了 the_widget 动作钩子,允许开发者干预小部件显示过程。

代码示例

// 默认显示分类小部件
the_widget( 'WP_Widget_Categories' );

// 带设置显示分类小部件
the_widget( 'WP_Widget_Categories', 'dropdown=1&count=1' );

// 使用数组参数显示自定义小部件
$instance = array(
    'title' => 'Title',
    'text' => 'Text'
);
$args = array(
    'before_widget' => '<div class="custom-widget">',
    'after_widget' => '</div>',
    'before_title' => '<h2>',
    'after_title' => '</h2>'
);
the_widget( 'My_Custom_Widget', $instance, $args );

注意事项

  • 调用 the_widget() 前应验证小部件是否已注册,以避免错误日志记录。可参考用户贡献的 check_widget_registered() 辅助函数。
  • 小部件实例设置需符合对应小部件类的预期结构,例如分类小部件的 dropdown 和 count 参数。
  • 该函数自 WordPress 2.8.0 版本引入,适用于主题开发中的灵活小部件集成。

📄 原文内容

Outputs an arbitrary widget as a template tag.

Parameters

$widgetstringrequired
The widget’s PHP class name (see class-wp-widget.php).
$instancearrayoptional
The widget’s instance settings.

Default:array()

$argsarrayoptional
Array of arguments to configure the display of the widget.

  • before_widget string
    HTML content that will be prepended to the widget’s HTML output.
    Default <div class="widget %s">, where %s is the widget’s class name.
  • after_widget string
    HTML content that will be appended to the widget’s HTML output.
    Default </div>.
  • before_title string
    HTML content that will be prepended to the widget’s title when displayed.
    Default <h2 class="widgettitle">.
  • after_title string
    HTML content that will be appended to the widget’s title when displayed.
    Default </h2>.

Default:array()

More Information

For parameter $widget, The classes for the widgets included with WordPress are:

Archives widget

Display a monthly archive list.

<br>
 <br>

  • widget’s classname: widget_archive
  • instance:
    title
    The title of archive list. Default: __('Archives')
    count
    Display number of posts in each archive (1). The show_post_count parameter of wp_get_archives. Default: 0 (hide)
    dropdown
    Display as drop-down list (1). Default: 0 (an unordered list)

Examples

Default usage: <br>
 <br>

Display drop-down list: <br>
 <br>

Calendar widget

Displays a Calendar.

<br>
 <br>

  • widget’s classname: widget_calendar
  • instance:
    title
    The title of calendar. Default:  

Example

Default usage: <br>
 <br>

Categories widget

Displays a list of categories.

<br>
 <br>

  • widget’s classname: widget_categories
  • instance:
    title
    The title of categories list. Default: __( 'Categories' )
    count
    Display number of posts in each category. The show_count parameter of wp_dropdown_categories or wp_list_categories. Default: 0 (hide)
    hierarchical
    Display sub-categories as nested items inside the parent category (1). Default: 0 (in-line)
    dropdown
    Display as dropdown list (1). Default: 0 (an unordered list)

Examples

Default usage: <br>
 <br>

Display a dropdown list with number of posts. <br>
 <br>

Custom HTML widget

Displays arbitrary HTML. <br>
 <br>

  • widget’s classname: widget_custom_html
  • instance:
    title
    The title for the content. Default: <i></i>
    content
    arbitrary HTML. Default: <i></i>

Examples

Default usage: <br>
  'Example''content' => '<p>Basic example.</p>')); ?><br>

Displays a list of links (blogroll) in categories.

<br>
 <br>

  • widget’s classname:
  • instance:
    title
    The title of the Links section.
    category
    Link category IDs , separated by commas, to display. The category parameter of wp_list_bookmarks. Default: false (display all of link categories)
    description
    Display description of link (1 – true). The show_description parameter. Default: false (hide)
    rating
    Display rating of link (1- true). The show_rating parameter. Default: false (hide)
    images
    Display image of link (1 – true). The show_images parameter. Default: true (show)
    name
    If display link image, output link name to the alt attribute. The show_name parameter. Default: false

Examples

Default usage: <br>
 <br>

Display lists in category IDs 2 or 3: <br>
 <br>

Meta widget

Display site meta. (Log in/out, admin, feed and WordPress links )

<br>
 <br>

  • widget’s classname: widget_meta
  • instance:
    title
    The title of meta section. Default: __( 'Meta' )

Example

Default usage: <br>
 <br>

Pages widget

Display a list of Pages.

<br>
 <br>

  • widget’s classname: widget_pages
  • instance:
    title
    The title of Pages list. Default: __( 'Pages' )
    sortby
    The sort_column parameter of wp_list_pages. Default: menu_order
    exclude
    Page IDs, separated by commas, to be excluded from the list. Default: null (show all of Pages)

Examples

Default usage:

 the_widget( 'WP_Widget_Pages' );

Contents

as the heading, sort by last modified date:

 the_widget('WP_Widget_Pages', 'title=Contents&sortby;=post_modified', 'before_title=

&after;_title=

');

Recent Comments widget

Display to a list of recent comments.

<br>
 <br>

  • widget’s classname: widget_recent_comments
  • instance:
    title
    The title of comment list. Default: __( 'Recent Comments' )
    number
    Number of comments to show (at most 15). Default: 5

Example

Default usage: <br>
 <br>

Recent Posts widget

Display to a list of recent posts.

<br>
 <br>

  • widget’s classname: widget_recent_entries
  • instance:
    title
    The title of post list. Default: __('Recent Posts')
    number
    Number of posts to show (at most 15). Default: 10

Example

Default usage: <br>
 <br>

RSS widget

Display a list of entries from any RSS or Atom feed.

<br>
 <br>

  • widget’s classname:
  • instance :
    title
    The title of list
    Default: the title inherited from the RSS or Atom feed
    url
    RSS or Atom feed URL to include.
    items
    the number of RSS or Atom items to display
    show_summary
    show_author
    show_date

Example

Default usage: <br>
 <br>

Search widget

<br>
 <br>

  • widget’s classname: widget_search
  • instance:
    title
    The title of search form. Default: null

Example

Default usage: <br>
 <br>

Tag Cloud widget

<br>
 <br>

  • widget’s classname:
  • instance:
    title
    The title of tag cloud. default: __( 'Tags' )
    taxonomy
    The taxonomy the cloud will draw tags from. default: post_tag

Example

Default usage: <br>
 <br>

Text widget

<br>
 <br>

  • widget’s classname: widget_text
  • instance:
    • title
    • text
    • filter

Example

Default usage: <br>
 <br>

Custom Widget

Display custom widget in template.

<br>
 <br>

  • widget’s classname: WIDGET CLASS NAME (for example see below)
  • instance: (optional)
  • arguments: (optional)

Example

Default usage:

class <strong>My_Custom_Widget</strong> extends WP_Widget<br>
{<br>
/* your code* /<br>
}

<br>
 <br>

Source

function the_widget( $widget, $instance = array(), $args = array() ) {
	global $wp_widget_factory;

	if ( ! isset( $wp_widget_factory->widgets[ $widget ] ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: %s: register_widget() */
				__( 'Widgets need to be registered using %s, before they can be displayed.' ),
				'<code>register_widget()</code>'
			),
			'4.9.0'
		);
		return;
	}

	$widget_obj = $wp_widget_factory->widgets[ $widget ];
	if ( ! ( $widget_obj instanceof WP_Widget ) ) {
		return;
	}

	$default_args          = array(
		'before_widget' => '<div class="widget %s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h2 class="widgettitle">',
		'after_title'   => '</h2>',
	);
	$args                  = wp_parse_args( $args, $default_args );
	$args['before_widget'] = sprintf( $args['before_widget'], $widget_obj->widget_options['classname'] );

	$instance = wp_parse_args( $instance );

	/** This filter is documented in wp-includes/class-wp-widget.php */
	$instance = apply_filters( 'widget_display_callback', $instance, $widget_obj, $args );

	if ( false === $instance ) {
		return;
	}

	/**
	 * Fires before rendering the requested widget.
	 *
	 * @since 3.0.0
	 *
	 * @param string $widget   The widget's class name.
	 * @param array  $instance The current widget instance's settings.
	 * @param array  $args     An array of the widget's sidebar arguments.
	 */
	do_action( 'the_widget', $widget, $instance, $args );

	$widget_obj->_set( -1 );
	$widget_obj->widget( $args, $instance );
}

Hooks

do_action( ‘the_widget’, string $widget, array $instance, array $args )

Fires before rendering the requested widget.

apply_filters( ‘widget_display_callback’, array $instance, WP_Widget $widget, array $args )

Filters the settings for a particular widget instance.

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Show widget with default settings:

    the_widget( 'WP_Widget_Categories' );

    Show widget with settings:

    the_widget( 'WP_Widget_Categories', 'dropdown=1&count;=1' );

    Show widget with custom arguments:

    $instance = array(
    	'dropdown' => 1,
    	'count'    => 1,
    );
    $args = array(
    	'before_widget' => '<div id="%1$s" class="widget %2$s">', 
    	'after_widget' => '</div>',
    	'before_title' => '<div class="widget-title">',
    	'after_title' => '</div>'
    );
    the_widget( 'WP_Widget_Categories', $instance, $args );

  2. Skip to note 6 content

    This function will be showing error in the log file “Widgets need to be registered using register_widget() , before they can be displayed” if the specified widget name is not exists.
    The widgets on this page can be removed by some ways even they are core widgets.

    To prevent this, you need to check before call the_widget() that widget is really regietered/exists.
    But sadly, currently there is no function to check it easily. However, the code below can help.

    <br />
    function check_widget_registered(string $widget_class_name) {<br />
    global $wp_widget_factory;</p>
    <p> if ( ! empty( $wp_widget_factory->widgets ) && array_key_exists( $widget_class_name, $wp_widget_factory->widgets ) ) {<br />
    return true;<br />
    } else {<br />
    return false;<br />
    }<br />
    }<br />

    The code above generated by Gemini.

    To use,

    <br />
    if (check_widget_registered('WP_Widget_Recent_Posts')) {<br />
    the_widget('WP_Widget_Recent_Posts');<br />
    }<br />