所以我有两个功能。一旦返回一些信息,我试图在我的第二个函数中访问它,但这当前是空的/这是我的第一个函数代码:
function get_current_user_role_custom() {
global $wp_roles;
$current_user = wp_get_current_user();
$roles = $current_user->roles;
$role = array_shift( $roles );
return isset( $wp_roles->role_names[ $role ] ) ? translate_user_role( $wp_roles->role_names[ $role ] ) : FALSE;
}
$user_role = get_current_user_role_custom();
第二个函数(我试图使用$user_role
变量:
function new_customer_registered_send_email_admin() {
//variables
global $user_role;
global $current_user;
$current_user = wp_get_current_user();
ob_start();
do_action('woocommerce_email_header', 'New customer registered');
$email_header = ob_get_clean();
ob_start();
do_action('woocommerce_email_footer');
$email_footer = ob_get_clean();
woocommerce_mail(
get_bloginfo('admin_email'),
get_bloginfo('name').' - New customer registered',
$email_header.'<p>User Role: ' . $user_role . '</p>'.$email_footer
);
}
add_action('new_customer_registered', 'new_customer_registered_send_email_admin');
答案 0 :(得分:0)
您最好将其作为参数new_customer_registered_send_email_admin($user_role)
传递,而不是将user_role用作全局变量。使用全局变量可能会导致代码执行不可预测并且难以调试。
在您的情况下,您使用的是wordpress add_action方法。要将变量传递给此方法,请参阅此链接 can I pass arguments to my function through add_action?
答案 1 :(得分:0)
解决方案是不使用$user_role
变量而是检索函数的结果,如下所示:
$email_header.'<p>User Role: ' . get_current_user_role_custom() . '</p>'.$email_footer
答案 2 :(得分:0)
除非你有充分的理由说明为什么必须使用全局变量(几乎不是这种情况),所以不要使用全局变量。而是使用参数/参数将变量及其值传递给函数。
尝试这样的事情:
// ### Define Functions ###
function get_current_user_role_custom($wp_roles) {
$current_user = wp_get_current_user();
$roles = $current_user->roles;
$role = array_shift( $roles );
return isset( $wp_roles->role_names[ $role ] ) ? translate_user_role( $wp_roles->role_names[ $role ] ) : FALSE;
}
function new_customer_registered_send_email_admin($user_role) {
//variables
$current_user = wp_get_current_user();
ob_start();
do_action('woocommerce_email_header', 'New customer registered');
$email_header = ob_get_clean();
ob_start();
do_action('woocommerce_email_footer');
$email_footer = ob_get_clean();
woocommerce_mail(
get_bloginfo('admin_email'),
get_bloginfo('name').' - New customer registered',
$email_header.'<p>User Role: ' . $user_role . '</p>'.$email_footer
);
}
// ### Call Functions ###
// as I cannot see where this variable comes from, you need to modify the follwoing line yourself appropriately ;)
$wp_roles = get_wp_roles_somehow();
$user_role = get_current_user_role_custom($wp_roles);
if ($user_role !== FALSE) {
new_customer_registered_send_email_admin($user_role);
add_action('new_customer_registered', 'new_customer_registered_send_email_admin');
} else {
// handle error somehow
}