首页 > 解决方案 > 如何从数据库中加载 user_email 并将其发布到 Php wp_mail() 函数的 $to 中

问题描述

我正在尝试使用 wordpress 的 PHP wp_mail() 函数向注册用户发送生日邮件。但是,我无法发送电子邮件。请进入下面的代码:


# Get user ID
$id = get_current_user_id();

global $wpdb;

//query to extract  birthdate from database 
$result = $wpdb->get_results("SELECT um.meta_value FROM `wp_usermeta` AS um WHERE um.user_id = $id AND um.meta_key = 'birth_date'");

//query to extract email from database
$query= $wpdb->get_results("SELECT u.user_email FROM `wp_users` AS u WHERE u.ID = $id");


//load data from database and store it in user_name variable

foreach ($query as $row1) {
    $user_name =  $row1->user_email;
       
        
}
//birth_date 
$newDate = date("d-m", strtotime($birth_date ));  
//echo "birth date format is: ".$newDate;  

//present date
//$now = time();
//$newNow= date("d-m", strtotime($now));  
$newNow = date("d-m");
//echo "Today date format is: ".$newNow; 


if ($newDate == $newNow) { 
    
    $to = $user_name;
    $subject = 'Happy Birthday';
       

    $body = 'Hello Gaurav';
    wp_mail( $to, $subject,$body );

 
}

?>


在上面的代码中,我尝试放入$to=$user_name$to 部分,它不会向注册用户发送电子邮件。但是,如果我手动输入整个电子邮件地址,即 $to= "xyz@gmail.com"xyz 用户成功接收电子邮件。

标签: phpwordpressphpmailer

解决方案


我修改了你的代码。你应该检查是否email为空。试试下面的代码。

对于电子邮件,您可以让用户使用get_user_by()

$user = get_user_by( 'id', get_current_user_id() );

要检索用户元数据,您可以使用get_user_meta()函数。

$birth_date = get_user_meta( $user->ID, 'birth_date', true );

function sent_birthday_mail(){

    $user = get_user_by( 'id', get_current_user_id() );

    if ( $user ) {
        $email      = $user->user_email;
        $birth_date = get_user_meta( $user->ID, 'birth_date', true );
        $birth_date = date("d-m", strtotime( $birth_date ) );
        $today_date = date("d-m");

        if ( $email != '' && $today_date == $birth_date) { 
            $to      = $email;
            $subject = 'Happy Birthday';
            $body    = 'Hello '.$user->first_name;
            if( wp_mail( $to, $subject, $body ) ){
                echo "sent";
            }
        }
    }

}
add_action( 'init', 'sent_birthday_mail', 10, 1 );

wp_mail_failed此外,您可以使用 WP操作挂钩检查 wp_mail 错误。

// show wp_mail() errors
add_action( 'wp_mail_failed', 'onWPMailError', 10, 1 );
function onWPMailError( $wp_error ) {
    echo "<pre>"; print_r($wp_error); echo "</pre>";
}

推荐阅读