钩子文档

pre_update_option_{$option}

💡 云策文档标注

概述

pre_update_option_{$option} 是一个动态过滤器钩子,用于在特定选项值被序列化和更新到数据库之前进行过滤。它允许开发者修改选项的新值,从而覆盖原始值。

关键要点

  • 这是一个动态钩子,$option 部分对应选项名称,例如 pre_update_option_foo 用于过滤名为 "foo" 的选项。
  • 过滤器在选项值保存到数据库之前应用,可用于验证、修改或阻止更新。
  • 参数包括 $value(新值)、$old_value(旧值)和 $option(选项名称)。
  • 从 WordPress 4.4.0 版本开始添加了 $option 参数。

代码示例

add_action( 'init', 'myplugin_init' );

function myplugin_init() {
    add_filter( 'pre_update_option_foo', 'myplugin_update_field_foo', 10, 2 );
}

function myplugin_update_field_foo( $new_value, $old_value ) {
    $new_value = intval( $new_value );
    $new_value ++;
    return $new_value;
}

📄 原文内容

Filters a specific option before its value is (maybe) serialized and updated.

Description

The dynamic portion of the hook name, $option, refers to the option name.

Parameters

$valuemixed
The new, unserialized option value.
$old_valuemixed
The old option value.
$optionstring
Option name.

More Information

This filter is applied to the option value before being saved to the database; this allows the overriding value to be stored. To use this filter, you will need to add filters for specific options names, such as “pre_update_option_foo” to filter the option “foo“.

Source

$value = apply_filters( "pre_update_option_{$option}", $value, $old_value, $option );

Changelog

Version Description
4.4.0 The $option parameter was added.
2.6.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    add_action( 'init', 'myplugin_init' );
    
    function myplugin_init() {
    	add_filter( 'pre_update_option_foo', 'myplugin_update_field_foo', 10, 2 );
    }
    
    function myplugin_update_field_foo( $new_value, $old_value ) {
    	$new_value = intval( $new_value );
    	$new_value ++;
    	return $new_value;
    }