钩子文档

sanitize_key

💡 云策文档标注

概述

sanitize_key 过滤器用于在 sanitize_key() 函数处理后,对已清理的键字符串进行进一步过滤。它允许开发者基于原始键和已清理键执行自定义的额外清理操作。

关键要点

  • sanitize_key 过滤器在 sanitize_key() 函数执行后触发,传递 $sanitized_key 和 $key 作为参数。
  • 默认情况下,sanitize_key() 函数将字符串键转换为小写字母数字、短横线和下划线字符。
  • 过滤器可用于修改已清理的键,例如移除短横线,或基于原始键进行自定义处理。
  • 直接过滤原始键需谨慎,以避免返回 sanitize_key() 函数不允许的字符。

代码示例

add_filter( 'sanitize_key', 'remove_dashes_from_keys' );

function remove_dashes_from_keys( $key ) {
    return preg_replace( '/-/s', '', $key );
}
add_filter( 'sanitize_key', 'do_something_with_rawkeys', 10, 2 );

function do_something_with_rawkeys( $key, $rawkey ) {
    // do domething with $rawkey
    return $rawkey;
}

注意事项

直接过滤原始键($raw_key)不推荐,因为如果 sanitize_key() 函数更新,可能导致返回的键包含不允许的字符。


📄 原文内容

Filters a sanitized key string.

Parameters

$sanitized_keystring
Sanitized key.
$keystring
The key prior to sanitization.

More Information

  • By default, sanitize_key() function sanitize a string key, which is used as internal identifiers, into lowercase alphanumeric, dashes, and underscores characters. After sanitize_key() function has done its work, it passes the sanitized key through this sanitize_key filter.
  • The filter passes $key and $raw_key as parameters, which allows the user of this filter to perform additional sanitization based on these two keys.

Source

return apply_filters( 'sanitize_key', $sanitized_key, $key );

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example Migrated from Codex:

    Filtering the output

    Remove dashes from the string key after sanitize_key() function has done its work (dash is allowed by sanitize_key() function).

    add_filter( 'sanitize_key', 'remove_dashes_from_keys' );
    
    function remove_dashes_from_keys( $key ) {
        return preg_replace( '/-/s', '', $key );
    }

    Filtering the raw key

    You can interact with the raw key as second parameter of that filter. The raw key is the exact value passed to the sanitize_key() function. You could use it to make your own sanitization of the original key.

    Note: Direct filtering of the $raw_key is not recommended since if not filtered carefully or if sanitize_key() function ever gets updated, your filter may be returning a key with characters that is prohibited by sanitize_key() function.

    add_filter( 'sanitize_key', 'do_something_with_rawkeys', 10, 2 );
    
    function do_something_with_rawkeys( $key, $rawkey ) {
        // do domething with $rawkey
        return $rawkey;
    }