函数文档

maybe_add_existing_user_to_blog()

💡 云策文档标注

概述

maybe_add_existing_user_to_blog() 是一个 WordPress 函数,用于通过访问特定 URL 路径将现有用户添加到博客中。它依赖于存储在选项中的用户详细信息,并在成功添加或失败时显示相应消息。

关键要点

  • 函数通过检查 /newbloguser/{key}/ 路径触发,其中 {key} 是用于标识用户的哈希值。
  • 用户详细信息必须作为选项 'new_user_{key}' 保存,通常通过 WordPress 添加用户界面邀请用户时生成。
  • 函数使用 add_existing_user_to_blog() 添加用户,并在错误时调用 wp_die() 显示错误消息,成功时显示成功消息。
  • 相关函数包括 get_option(), delete_option(), is_wp_error(), __(), home_url(), admin_url() 等。

代码示例

function maybe_add_existing_user_to_blog() {
    if ( ! str_contains( $_SERVER['REQUEST_URI'], '/newbloguser/' ) ) {
        return;
    }

    $parts = explode( '/', $_SERVER['REQUEST_URI'] );
    $key   = array_pop( $parts );

    if ( '' === $key ) {
        $key = array_pop( $parts );
    }

    $details = get_option( 'new_user_' . $key );
    if ( ! empty( $details ) ) {
        delete_option( 'new_user_' . $key );
    }

    if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) ) {
        wp_die(
            sprintf(
                __( 'An error occurred adding you to this site. Go to the homepage.' ),
                home_url()
            )
        );
    }

    wp_die(
        sprintf(
            __( 'You have been added to this site. Please visit the homepage or log in using your username and password.' ),
            home_url(),
            admin_url()
        ),
        __( 'WordPress › Success' ),
        array( 'response' => 200 )
    );
}

注意事项

  • 此函数仅在多站点环境中有效,自 WordPress MU 3.0.0 版本引入。
  • 用户贡献笔记指出,“newbloguser” 路径名称可能已过时,因为 WordPress 已演变为更广泛的网站构建平台。
  • 确保用户详细信息正确存储为选项,否则添加过程会失败并显示错误。

📄 原文内容

Adds a new user to a blog by visiting /newbloguser/{key}/.

Description

This will only work when the user’s details are saved as an option keyed as ‘new_user_{key}’, where ‘{key}’ is a hash generated for the user to be added, as when a user is invited through the regular WP Add User interface.

Source

function maybe_add_existing_user_to_blog() {
	if ( ! str_contains( $_SERVER['REQUEST_URI'], '/newbloguser/' ) ) {
		return;
	}

	$parts = explode( '/', $_SERVER['REQUEST_URI'] );
	$key   = array_pop( $parts );

	if ( '' === $key ) {
		$key = array_pop( $parts );
	}

	$details = get_option( 'new_user_' . $key );
	if ( ! empty( $details ) ) {
		delete_option( 'new_user_' . $key );
	}

	if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) ) {
		wp_die(
			sprintf(
				/* translators: %s: Home URL. */
				__( 'An error occurred adding you to this site. Go to the <a href="%s">homepage</a>.' ),
				home_url()
			)
		);
	}

	wp_die(
		sprintf(
			/* translators: 1: Home URL, 2: Admin URL. */
			__( 'You have been added to this site. Please visit the <a href="%1$s">homepage</a> or <a href="%2$s">log in</a> using your username and password.' ),
			home_url(),
			admin_url()
		),
		__( 'WordPress › Success' ),
		array( 'response' => 200 )
	);
}

Changelog

Version Description
MU (3.0.0) Introduced.

User Contributed Notes