php - 如何从数据库中加载 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 用户成功接收电子邮件。
解决方案
我修改了你的代码。你应该检查是否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>";
}
推荐阅读
- azure-devops - 无法在 Microsoft Teams 中设置 Devops Pipelines 应用程序。应用程序卡住
- reactjs - React - 当作为道具传递时,父母的状态变化不会导致孩子的重新渲染?
- c# - 计算更多 foreach 循环的百分比
- typescript - 正确获取嵌套条件映射类型的类型
- javascript - 如何在nodejs中将mmddyyyy日期格式转换为mm/dd/yyyy
- json - 以 json 形式获取 firebase 实时数据库并映射
- ruby-on-rails - Rails:查找或初始化然后在参数中合并
- apache-spark - Spark 流式传输:公开 spark_streaming_* 指标
- apache-kafka - 调用 KStream.join() 后,Kafka 密钥附加了奇怪的字符
- dialogflow-es - 是否可以将消息推送到 Dialogflow 对话?