gpt4 book ai didi

php - 编写一个类以在 WordPress 中传递 add_action 参数

转载 作者:行者123 更新时间:2023-12-02 21:47:17 24 4
gpt4 key购买 nike

我正在使用钩子(Hook)user_register来写入变量$user_id。我想在函数内调用此 Hook ,并将变量 $pass 从父函数传递到函数 register_pass。一旦到达,$passuser_id 将按照第三方软件的协议(protocol)发送到第三方软件。

关键目标是$pass$user_id 放入同一个数组中,以便通过 SOAP 发送出去。

function random_pass_save($pass){

add_action( 'user_register', 'regiser_pass')
function register_pass($user_id){
.
.
.
code that processes both the $user_id, AND $pass and sends it to another piece of software
.
.
.
}

}

现在我已经对此进行了一些阅读,并且我不断有人建议使用类将变量从 add_action 调用传递到父函数等。原则上这是有道理的;据我了解,您几乎可以在任何地方访问该类(有点像全局变量,但不那么不稳定)。然而,我只是不明白如何将我所看到的例子应用到我的情况中。我以前没有使用过类,所以我想知道是否有人愿意引导我完成这个特定的应用程序。

最佳答案

如果我理解正确的话,您只需在创建用户时调用自定义函数即可。这些函数不必嵌套,并且是否是一个类并不重要。

添加钩子(Hook)并在其回调中调用传递数据的函数:

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 之前,并且包含用户名和密码。

但是好吧,让我们在一个类中完成它,它基于 this skeleton that I always use 。所有的解释都在代码注释中。

<?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();
}
}

关于php - 编写一个类以在 WordPress 中传递 add_action 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19306582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com