函数文档

wp_generate_password()

💡 云策文档标注

概述

wp_generate_password() 是 WordPress 核心函数,用于生成随机密码,基于定义的字符集,支持自定义长度和特殊字符选项。它使用 wp_rand() 提高随机性,优于 PHP 原生函数。

关键要点

  • 函数签名:wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ),返回字符串类型密码。
  • 参数说明:$length 控制密码长度(默认12),$special_chars 决定是否包含标准特殊字符(默认true),$extra_special_chars 用于包含额外特殊字符(默认false)。
  • 字符集:默认包含字母和数字;$special_chars 为 true 时添加 !@#$%^&*();$extra_special_chars 为 true 时添加 -_ []{}<>~`+=,.;:/?|。
  • 钩子:生成密码后执行 random_password 过滤器,允许自定义修改。
  • 相关函数:依赖 wp_rand() 生成随机数,被多个核心功能如用户注册、密码重置等调用。

代码示例

// 生成仅包含字母和数字的8位密码
wp_generate_password( 8, false, false );

// 生成包含所有字符类型的10位密码
wp_generate_password( 10, true, true );

// 生成用于URL缓存破坏的唯一哈希示例
$url = home_url( '/some-location' );
$url = add_query_arg( array(
    '_some_param' => wp_generate_password( 32, false, false )
), $url );
wp_safe_redirect( $url );

注意事项

  • 该函数自 WordPress 2.5.0 引入,适用于需要安全随机密码的场景,如用户账户、密钥生成等。
  • 使用 wp_rand() 增强安全性,避免使用 PHP 的 rand() 或 mt_rand() 以减少可预测性。
  • 在 AJAX 处理、恢复模式、会话令牌等核心功能中广泛使用,确保集成时遵循默认参数或根据需求调整。

📄 原文内容

Generates a random password drawn from the defined set of characters.

Description

Uses wp_rand() to create passwords with far less predictability than similar native PHP functions like rand() or mt_rand().

Parameters

$lengthintoptional
The length of password to generate.

Default:12

$special_charsbooloptional
Whether to include standard special characters.

Default:true

$extra_special_charsbooloptional
Whether to include other special characters.
Used when generating secret keys and salts.

Default:false

Return

string The random password.

More Information

This function executes the random_password filter after generating the password.

Normal characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

Special characters: !@#$%^&*()

Extra special characters: -_ []{}~`+=,.;:/?|

Source

function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	if ( $special_chars ) {
		$chars .= '!@#$%^&*()';
	}
	if ( $extra_special_chars ) {
		$chars .= '-_ []{}<>~`+=,.;:/?|';
	}

	$password = '';
	for ( $i = 0; $i < $length; $i++ ) {
		$password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
	}

	/**
	 * Filters the randomly-generated password.
	 *
	 * @since 3.0.0
	 * @since 5.3.0 Added the `$length`, `$special_chars`, and `$extra_special_chars` parameters.
	 *
	 * @param string $password            The generated password.
	 * @param int    $length              The length of password to generate.
	 * @param bool   $special_chars       Whether to include standard special characters.
	 * @param bool   $extra_special_chars Whether to include other special characters.
	 */
	return apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars );
}

Hooks

apply_filters( ‘random_password’, string $password, int $length, bool $special_chars, bool $extra_special_chars )

Filters the randomly-generated password.

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 9 content

    You can use the wp_generate_password() function to create a unique hash that can be added as a parameter to URLs. This is useful in scenarios such as cache busting (forcing the browser to re-fetch the page instead of using a cached version) or generating unique referral links.

    Here’s an example of how to implement this:

    $url = home_url( '/some-location' ); // Get some URL of your WordPress site
    $url = add_query_arg( array(
        '_some_param' => wp_generate_password( 32, false, false ) // Generate a unique hash
    ), $url );
    
    wp_safe_redirect( $url ); // Safely redirect to the new URL

    You can replace home_url() with any other URL you want to use as the base.