Codex

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

Difference between revisions of "Widgets API"

(Updated by V4.3)
(Example)
 
(10 intermediate revisions by 10 users not shown)
Line 52: Line 52:
 
That base class also contains information about the functions that must be extended to get a working widget.
 
That base class also contains information about the functions that must be extended to get a working widget.
   
The <tt>WP_Widget</tt> class is located in {{Trac|wp-includes/widgets.php}}.
+
The <tt>WP_Widget</tt> class is located in {{Trac|wp-includes/class-wp-widget.php}}.
   
 
=== Default Usage ===
 
=== Default Usage ===
Line 62: Line 62:
 
*/
 
*/
 
public function __construct() {
 
public function __construct() {
  +
$widget_ops = array(
// widget actual processes
 
  +
'classname' => 'my_widget',
  +
'description' => 'My Widget is awesome',
  +
);
  +
parent::__construct( 'my_widget', 'My Widget', $widget_ops );
 
}
 
}
   
Line 89: Line 93:
 
* @param array $new_instance The new options
 
* @param array $new_instance The new options
 
* @param array $old_instance The previous options
 
* @param array $old_instance The previous options
  +
*
  +
* @return array
 
*/
 
*/
 
public function update( $new_instance, $old_instance ) {
 
public function update( $new_instance, $old_instance ) {
Line 100: Line 106:
 
<pre>
 
<pre>
 
add_action( 'widgets_init', function(){
 
add_action( 'widgets_init', function(){
register_widget( 'My_Widget' );
+
register_widget( 'My_Widget' );
 
});
 
});
 
</pre>
 
</pre>
Line 106: Line 112:
 
<pre>
 
<pre>
 
add_action('widgets_init',
 
add_action('widgets_init',
create_function('', 'return register_widget("My_Widget");')
+
create_function('', 'return register_widget("My_Widget");')
 
);
 
);
 
</pre>
 
</pre>
Line 126: Line 132:
 
parent::__construct(
 
parent::__construct(
 
'foo_widget', // Base ID
 
'foo_widget', // Base ID
__( 'Widget Title', 'text_domain' ), // Name
+
esc_html__( 'Widget Title', 'text_domain' ), // Name
array( 'description' => __( 'A Foo Widget', 'text_domain' ), ) // Args
+
array( 'description' => esc_html__( 'A Foo Widget', 'text_domain' ), ) // Args
 
);
 
);
 
}
 
}
Line 142: Line 148:
 
echo $args['before_widget'];
 
echo $args['before_widget'];
 
if ( ! empty( $instance['title'] ) ) {
 
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
+
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
 
}
 
}
echo __( 'Hello, World!', 'text_domain' );
+
echo esc_html__( 'Hello, World!', 'text_domain' );
 
echo $args['after_widget'];
 
echo $args['after_widget'];
 
}
 
}
Line 156: Line 162:
 
*/
 
*/
 
public function form( $instance ) {
 
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
+
$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
 
?>
 
?>
 
<p>
 
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
+
<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 $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
+
<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 ); ?>">
 
</p>
 
</p>
 
<?php
 
<?php
Line 177: Line 183:
 
public function update( $new_instance, $old_instance ) {
 
public function update( $new_instance, $old_instance ) {
 
$instance = array();
 
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
+
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';
   
 
return $instance;
 
return $instance;
Line 195: Line 201:
 
</pre>
 
</pre>
   
Note : You must use <tt>get_field_name()</tt> and <tt>get_field_id()</tt> function to generate form element name and id.
+
Note : You must use <tt>[[Function_Reference/get_field_name|get_field_name()]]</tt> and <tt>get_field_id()</tt> function to generate form element name and id.
   
 
=== Example With Namespaces ===
 
=== Example With Namespaces ===
Line 259: Line 265:
 
== Resources ==
 
== Resources ==
 
* [https://make.wordpress.org/core/2015/07/02/deprecating-php4-style-constructors-in-wordpress-4-3/ Deprecating PHP4 style constructors in WordPress 4.3.]
 
* [https://make.wordpress.org/core/2015/07/02/deprecating-php4-style-constructors-in-wordpress-4-3/ Deprecating PHP4 style constructors in WordPress 4.3.]
* [http://docs.layerswp.com/doc/notice-the-called-constructor-method-for-wp_widget-is-deprecated-since-version-4-3-0-use-__construct/ Notice: The called constructor method for WP_Widget is deprecated since version 4.3.0! Use __construct()]
+
* [https://w3guy.com/fix-notice-called-constructor-method-wp_widget-deprecated/ How to Fix – Notice: The called constructor method for WP_Widget is deprecated]
 
* [http://generatewp.com/sidebar/ WordPress Sidebar Generator]
 
* [http://generatewp.com/sidebar/ WordPress Sidebar Generator]
   

Latest revision as of 16:08, 24 April 2018

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
	 *
	 * @return array
	 */
	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+:

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

Example

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() {
		parent::__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' );
		?>
		<p>
		<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 ); ?>">
		</p>
		<?php 
	}

	/**
	 * 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'] ) ) ? sanitize_text_field( $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

Resources

Related

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