in_widget_form
Fires at the end of a widget settings form. Allows you to output additional fields for classic widgets.
The action also fires when the settings for the “Legacy Widget” block are generated through the REST API.
The action does not fire if the widget_form_callback filter returned false.
If a widget does not have its own form, WP_Widget::form() returns the string noform. When adding fields, set $return to null, otherwise WordPress may consider that the widget has no settings.
The action only outputs fields. To save their values, use the widget_update_callback filter.
The standard text about missing settings, which a widget without its own form outputs, can be hidden with CSS if necessary.
Usage
add_action( 'in_widget_form', 'wp_kama_in_widget_form_action' );
/**
* Function for `in_widget_form` action-hook.
*
* @param WP_Widget $widget The widget instance (passed by reference).
*
* @return void
*/
function wp_kama_in_widget_form_action( $widget ){
// action...
}
- $widget(WP_Widget)
- The current widget object. Passed by reference.
- $return(null|string)
- The value returned by the widget form method. The standard method returns
noform.
Passed by reference. Set it tonullif you add fields to a widget without its own form. - $instance(array)
- The current settings of the widget instance.
Examples
#1 Adding a field to all classic widgets
Let's add a text field Note and save its value together with the widget settings.
<?php
add_action( 'in_widget_form', 'wp_kama_add_widget_note_field', 10, 3 );
function wp_kama_add_widget_note_field( $widget, &$return, $instance ) {
$value = $instance['wp_kama_note'] ?? '';
$id = $widget->get_field_id( 'wp_kama_note' );
$name = $widget->get_field_name( 'wp_kama_note' );
$return = null;
?>
<p>
<label for="<?php echo esc_attr( $id ); ?>">
<?php esc_html_e( 'Note', 'my-plugin' ); ?>
</label>
<input
type="text"
class="widefat"
id="<?php echo esc_attr( $id ); ?>"
name="<?php echo esc_attr( $name ); ?>"
value="<?php echo esc_attr( $value ); ?>"
>
</p>
<?php
}
add_filter( 'widget_update_callback', 'wp_kama_save_widget_note', 10, 4 );
function wp_kama_save_widget_note( $instance, $new_instance, $old_instance, $widget ) {
if ( isset( $new_instance['wp_kama_note'] ) ) {
$instance['wp_kama_note'] = sanitize_text_field( $new_instance['wp_kama_note'] );
} else {
unset( $instance['wp_kama_note'] );
}
return $instance;
}Changelog
| Since 2.8.0 | Introduced. |
Where the hook is called
do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) );
do_action_ref_array( 'in_widget_form', array( &$widget_object, &$return, $instance ) );