Wordpress 如何将变量传递到函数中

Wordpress 如何将变量传递到函数中,wordpress,Wordpress,我尝试使用SMTP在Wordpress中发送电子邮件,代码如下,并且可以正常工作 function wow_phpmailer_init( $phpmailer ) { $phpmailer->SMTPAuth = true; $phpmailer->Host = 'mail.gmail.com'; $phpmailer->Port = '465'; $phpmailer->Username = 'my_email@gmail.com'; $phpmailer->

我尝试使用SMTP在Wordpress中发送电子邮件,代码如下,并且可以正常工作

function wow_phpmailer_init( $phpmailer ) {

$phpmailer->SMTPAuth = true;
$phpmailer->Host = 'mail.gmail.com';
$phpmailer->Port = '465';
$phpmailer->Username = 'my_email@gmail.com';
$phpmailer->Password = 'mypassword';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Mailer = 'smtp';

}
add_action( 'phpmailer_init', 'wow_phpmailer_init' );
现在,我需要为每个SMTP信息使用动态值,例如:

function wow_phpmailer_init( $phpmailer ) {

$phpmailer->SMTPAuth = true;
$phpmailer->Host = get_post_meta( $id, 'smtp_host', true );
$phpmailer->Port = get_post_meta( $id, 'smtp_port', true );
$phpmailer->Username = get_post_meta( $id, 'smtp_usr', true );
$phpmailer->Password = get_post_meta( $id, 'smtp_pass', true );
$phpmailer->SMTPSecure = get_post_meta( $id, 'smtp_encrypt', true );
$phpmailer->Mailer = 'smtp';

}
add_action( 'phpmailer_init', 'wow_phpmailer_init' );

问题是如何在函数wow\u phpmailer\u init($phpmailer)中传递动态$id而不使用全局var(例如全局$id;)等?

缺少一些上下文,因为我不确定do\u操作('phpmailer\u init')发生在哪里。最有可能的是它在你的循环中的某个地方,或者在一个正在计算帖子id的地方。只要增加add_action函数的参数计数,就可以根据需要将尽可能多的变量传递给do_操作

<?php
// function signature
function wow_phpmailer_init( $phpmailer, $id ) {
    // do stuff
}
// argument count is the 4th parameter
add_action('phpmailer_init', 'wow_phpmailer_init', 10, 2);

// somewhere else in your code you have something like this
do_action('phpmailer_init', $phpmailer, $post_id);

谢谢@dgilmore,phpmailer_init是默认的WP操作钩子,请参见此处使用代码时我们得到的通知:未定义变量:phpmailer error。为什么?我以为钩子是定制的。我明白了,这是wp_邮件的一部分。您只是想获取当前的帖子id吗?该函数是否会获取_ID();为您工作?您好,我们已经获得了帖子ID,但不知道如何将帖子ID添加到wow_phpmailer_init函数中。因此,您的代码仍然与上下文无关,因为我不知道何时调用wp_邮件、何时计算ID以及何时设置过滤器。如果你能控制这些事情,那么关闭可能是你最好的选择。我已经编辑了我的答案。
<?php
$id = ;// calculated id
add_action('phpmailer_init', function($phpmailer) use ($id) {
    // do stuff
});
wp_mail(); // send mail, which calls do_action('phpmailer_init')