如果我理解这一点,您只需要在创建用户时调用自定义函数。这些函数不必嵌套,这是否是一个类也没关系。
添加钩子并在其回调中,调用传递数据的函数:
add_action( 'user_register', 'register_pass' );
function register_pass( $user_id )
{
$password = get_the_password_somehow_with( $user_id ); // <--- problem
random_pass_save( $user_id, $password );
}
function random_pass_save( $user_id, $password )
{
// do your thing
}
这个问题可以用 hook 来解决check_passwords
,它发生在之前user_register
并且包含用户名和密码。
但是好的,让我们在一个类中进行,它基于我一直使用的这个骨架。所有的解释都在代码注释中。
<?php
/**
* Plugin Name: Testing a Singleton
* Plugin URI: http://stackoverflow.com/questions/19306582
* Version: 0.1
* Author: brasofilo
* Author URI: http://wordpress.stackexchange.com/users/12615/brasofilo
*/
# Start the plugin in a safe point
add_action(
'plugins_loaded',
array( B5F_Demo_SO_19306582::get_instance(), 'plugin_setup' )
);
class B5F_Demo_SO_19306582
{
# Singleton
protected static $instance = NULL;
# Store new user data (id, name, password)
private $user_data;
# Leave empty
public function __construct() {}
# Singleton
public static function get_instance()
{
NULL === self::$instance and self::$instance = new self;
return self::$instance;
}
# Start our action hooks
public function plugin_setup()
{
add_action( 'check_passwords', array( $this, 'check_pass' ), 10, 3 );
add_action( 'user_register', array( $this, 'user_register_action' ) );
}
# Confirms that passwords match when registering a new user
public function check_pass( $user, $pass1, $pass2 )
{
// They match, let's add data to our private property
if( $pass1 == $pass2 )
$this->user_data = array( 'user' => $user, 'pass' => $pass1 );
}
# Add the ID of a newly registered user to our private property
# Now we have all the data and can call our final method
public function user_register_action( $user_id )
{
$this->user_data['user_id'] = $user_id;
$this->external_save();
}
# In this method we do our thing with all the information
# previously stored in the private property
public function external_save()
{
var_dump( $this->user_data );
die();
}
}