widget_update_callback
云策文档标注
概述
widget_update_callback 是一个 WordPress 过滤器钩子,用于在小部件设置保存前进行过滤。开发者可以通过此钩子修改或验证小部件的实例数据,返回 false 可以阻止设置更新。
关键要点
- 这是一个过滤器钩子,允许在小部件设置保存前修改 $instance 数组。
- 参数包括 $instance(当前设置)、$new_instance(新设置)、$old_instance(旧设置)和 $widget(当前小部件实例)。
- 返回 false 可以短路小部件的更新过程,阻止设置保存。
- 常用于添加或验证自定义小部件字段,确保数据正确性。
代码示例
add_filter( 'widget_update_callback', 'wpdocs_update_custom_field_in_widget_form', 10, 2 );
function wpdocs_update_custom_field_in_widget_form( $instance, $new_instance ) {
$instance['column'] = ! empty( $new_instance['column'] ) ? $new_instance['column'] : '';
return $instance;
}注意事项
- 不要覆盖 WP_Widget::update_callback() 方法,应使用此钩子进行自定义处理。
- 确保正确处理参数,避免数据丢失或错误。
- 此钩子自 WordPress 2.8.0 版本引入,兼容性良好。
原文内容
Filters a widget’s settings before saving.
Description
Returning false will effectively short-circuit the widget’s ability to update settings.
Parameters
$instancearray-
The current widget instance’s settings.
$new_instancearray-
Array of new widget settings.
$old_instancearray-
Array of old widget settings.
$widgetWP_Widget-
The current widget instance.
Source
$instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 2 content
Razon Komar Pal
You may filter any field that already registered. For testing, Firstly we create a custom widget field end of the each widgets control form.
if ( ! function_exists( 'wpdocs_display_custom_field_in_widget_form' ) ) { add_action( 'in_widget_form', 'wpdocs_display_custom_field_in_widget_form', 10, 3 ); /** * Append custom field end of the widgets control form * Fires at the end of the widget control form. */ function wpdocs_display_custom_field_in_widget_form( $widget, $return, $instance ) { $column = isset( $instance['column'] ) ? $instance['column'] : ''; ob_start(); ?> <label for="<?php echo esc_attr( get_field_id( 'itclan_bs_grid_class' ) ) ?>"> <input class="widefat" value="" id="<?php echo esc_attr( get_field_id( 'column' ) ) ?>" name="<?php echo esc_attr( get_field_name( 'column' ) ) ?>" type="text" /> </label> </pre> <p>Now, we filter widget’s settings before saving. It will save our custom field <code>column</code> data.</p> <pre class="wp-block-code"><code lang="php" class="language-php line-numbers">if ( ! function_exists( 'wpdocs_update_custom_field_in_widget_form' ) ) { add_action( 'widget_update_callback', 'wpdocs_update_custom_field_in_widget_form', 10, 2 ); /** * Update widget fields * Filters a widget’s settings before saving. */ function wpdocs_update_custom_field_in_widget_form( $instance, $new_instance ) { $instance['column'] = ! empty( $new_instance['column'] ) ? $new_instance['column'] : ''; return $instance; } }