Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Widgets API


WordPress 是一套具备快速,轻量,并容易开发特点的开源程序. 为了保持这样的特性, 开发团队 会将需要的新功能谨慎的添加到 WordPress 中去. 不过,用户通常会需要将额外的功能添加到 WordPress 中来满足他们的需求. 这个开发文档为任何希望修改,扩展或贡献 WordPress 的开发者提供指南和参考.

你可以在此查阅开发过程中遇到的的常见问题 开发文档 FQA

注意: 文档阅读前提

尽管 WordPress 可下载文件的调整权限仅掌握在几个不同的程序员手中,但每个 WordPress 用户都能够修改 WordPress 的核心代码,从而使得 WordPress实现高度定制化服务.

Plugin Development

  • Plugin Developer Handbook - The best starting place for learning about how to develop plugins
  • WordPress Coding Standards - General information about coding standards for WordPress development
  • Debugging in WordPress - Reference and guide for using the built-in debugging system in WordPress.
  • Data Validation - A must-read for WordPress plugin authors. Describes the functions used by WordPress to validate and sanitize data. Plugin authors should be familiar with these functions and ideas.
  • Plugin Submission and Promotion - Once you have written your plugin, here are some hints on distributing it widely
  • Migrating Plugins and Themes - Contains information on how to upgrade your Plugin so it will work from version to version of WordPress
  • Function Reference - Complete PHP function reference for WordPress
  • Global Variables - A list of all global variables created by WordPress
  • Post Types - Creating new types of posts other than the posts that display on the main loop.
  • Taxonomies - Creating new types of taxonomies other than the built-in ones.
  • Reserved Terms - A list of reserved terms in WordPress.


  • Plugin API - Hooks, Actions, and Filters to use in your Plugins (version 2.1; has links to older version articles)
  • Shortcode API - A tutorial and reference for the shortcode API (new in version 2.5)
  • Dashboard Widgets API - A reference with examples for adding new widgets to the admin dashboard.
  • Settings API - A reference with examples for adding new settings to existing settings screens.
  • Options API - Details about the generic option storage system.
  • Transients API - Details about the temporary/time-constrained data storage system.
  • Widgets API - A reference with examples for creating widgets for use in sidebars.
  • Quicktags API - A reference for adding buttons to the HTML editor.
  • Rewrite API - Details about the URL rewriting API.
  • Theme Customization API - Details about the API for Theme Customization screen.
  • Filesystem API - Reference for reading and writing local files to the filesystem to be done securely, on a variety of host types.

Contributing to WordPress

  • Contributing to WordPress - Main starting point if you would like to contribute to core WordPress development, documentation, support, translations, or financial health
  • Automated Testing - Testing WordPress using the automated test suite and how to use the tools and write test cases.
  • Release Philosophy - The philosophy of WordPress releases.

Forums, Lists, and Blogs

Other Information of Interest

  • Advanced Topics - Annotated list of many articles on advanced WordPress topics
  • Query Overview - Description of the WordPress query process used to find posts and display them
  • Reporting Bugs - Information on reporting and fixing WordPress bugs
  • Using Subversion - Introduction to SVN, the source code repository used by WordPress
  • Development Team - The members of the development team.

Other Resources

About WordPressGetting Started with WordPressWorking with WordPressBlog Design and LayoutAdvanced TopicsTroubleshootingDeveloper DocumentationCurrent Events
(Add your language)


This article is marked as in need of editing. You can help Codex by editing it.

Widgets API

This page contains the technical documentation for the WordPress Widgets API and is written for developers. If you're not a developer you may want to review the Widgets page.

In technical terms: a WordPress Widget is a PHP object that echoes string data to STDOUT when its widget() method is called. It's located in wp-includes/widgets.php.

Function Reference

Widget Functions
internal Functions

Developing Widgets

To create a widget, you only need to extend the standard WP_Widget class and some of its functions.

That base class also contains information about the functions that must be extended to get a working widget.

The WP_Widget class is located in wp-includes/class-wp-widget.php.

Default Usage

class My_Widget extends WP_Widget {

	 * Sets up the widgets name etc
	public function __construct() {
		$widget_ops = array( 
			'classname' => 'my_widget',
			'description' => 'My Widget is awesome',
		parent::__construct( 'my_widget', 'My Widget', $widget_ops );

	 * Outputs the content of the widget
	 * @param array $args
	 * @param array $instance
	public function widget( $args, $instance ) {
		// outputs the content of the widget

	 * Outputs the options form on admin
	 * @param array $instance The widget options
	public function form( $instance ) {
		// outputs the options form on admin

	 * Processing widget options on save
	 * @param array $new_instance The new options
	 * @param array $old_instance The previous options
	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved

The widget can then be registered using the widgets_init hook:

PHP 5.3+ only:

add_action( 'widgets_init', function(){
	register_widget( 'My_Widget' );

PHP 5.2+:

	create_function('', 'return register_widget("My_Widget");')


This sample code creates a Widget named Foo_Widget that has a settings form to change the display title.

 * Adds Foo_Widget widget.
class Foo_Widget extends WP_Widget {

	 * Register widget with WordPress.
	function __construct() {
			'foo_widget', // Base ID
			esc_html__( 'Widget Title', 'text_domain' ), // Name
			array( 'description' => esc_html__( 'A Foo Widget', 'text_domain' ), ) // Args

	 * Front-end display of widget.
	 * @see WP_Widget::widget()
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	public function widget( $args, $instance ) {
		echo $args['before_widget'];
		if ( ! empty( $instance['title'] ) ) {
			echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
		echo esc_html__( 'Hello, World!', 'text_domain' );
		echo $args['after_widget'];

	 * Back-end widget form.
	 * @see WP_Widget::form()
	 * @param array $instance Previously saved values from database.
	public function form( $instance ) {
		$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
		<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?></label> 
		<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">

	 * Sanitize widget form values as they are saved.
	 * @see WP_Widget::update()
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 * @return array Updated safe values to be saved.
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';

		return $instance;

} // class Foo_Widget

This sample widget can then be registered in the 'widgets_init' hook:

// register Foo_Widget widget
function register_foo_widget() {
    register_widget( 'Foo_Widget' );
add_action( 'widgets_init', 'register_foo_widget' );

Note : You must use get_field_name() and get_field_id() function to generate form element name and id.

Example With Namespaces

If you use PHP 5.3. with namespaces you should call the constructor directly as in the following example:

namespace a\b\c;

class My_Widget_Class extends \WP_Widget {
	function __construct() {
       	    parent::__construct( 'baseID', 'name' );
        // ... rest of functions

and call the register_widget() with:

add_action( 'widgets_init', function(){
     register_widget( 'a\b\c\My_Widget_Class' );

(see: http://stackoverflow.com/questions/5247302/php-namespace-5-3-and-wordpress-widget/5247436#5247436)

That's all. You will automatically get a multi-widget. No special tweaks needed any longer for that.

More information is available in the version 2.8 information.

Displaying Widgets and Widget Areas

There are at least 3 ways that Widgets can be displayed:

Widget Areas

The first, and most common, is by adding the desired Widget to a Widget Area via the Appearance -> Widgets menu in the Administration Screens.

WordPress comes with some predefined Widget Areas that each have unique identifiers (view the source of the Widgets page to see them) that you'll need to know in order to display the Widget Area. If the predefined Widget Areas are insufficient for your needs you may register a custom Widget Areas.

When you're ready you can display that Widget Area by inserting the following code into whichever Theme file you desire:

<?php if ( dynamic_sidebar('example_widget_area_name') ) : else : endif; ?>

That code displays all of the Widgets added to that Widget Area.

Display Widget Area Only If Active

Here's the code used in the sidebar.php file of the Twenty Fourteen Theme.

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
	<div id="primary-sidebar" class="primary-sidebar widget-area" role="complementary">
		<?php dynamic_sidebar( 'sidebar-1' ); ?>
	</div><!-- #primary-sidebar -->
<?php endif; ?>

This code checks to see if the new widget area is populated otherwise doesn't execute.

Independent Widgets

The second, and more technical, is via the_widget() method.

Tags: how do i display widgets, how do i display widget areas



Theme Support: add_theme_support(), remove_theme_support(), current_theme_supports()
Theme Features: sidebar, menus, post-formats, title-tag, custom-background, custom-header, custom-logo, post-thumbnails, automatic-feed-links, html5, editor-style, content_width