我有一个自定义帖子类型 crm,我需要在每个 crm 保存或更新后发送一封邮件。我使用 cmb2 来获取一些自定义元数据,例如主题、用户等。我知道当我使用两个参数(id 和 post)调用帖子不包含更新值时,在我的情况下,save_post
钩子会在保存后触发(根据 WordPress 法典) 。这是我的代码:save_post
function send_mail_to_user($id, $post){
$crm = $post;
$user_email = array();
if($crm->vc_all_vc == 'on'){
$args = array('orderby' => 'display_name');
$wp_user_query = new WP_User_Query($args);
$authors = $wp_user_query->get_results();
if (!empty($authors)) {
foreach ($authors as $author) {
array_push($user_email , $author->user_email );
}
}
}
else{
$to_users = $crm->vc_users;
$to_program = $crm->vc_program;
$to_group = $crm->vc_group;
$to_excode = $crm->vc_ex_code;
foreach ($to_users as $key => $value) {
$user_data = get_userdata($value);
array_push($user_email, $user_data->user_email);
}
foreach ($to_program as $key => $value) {
$users = get_users( array('meta_key' => 'programs' ) );
if($users){
foreach ($users as $index => $data) {
if(in_array($value , explode('#', $data->programs))){
if(! in_array($data->user_email, $user_email) )
{
array_push($user_email, $data->user_email);
}
}
}
}
}
foreach($to_group as $group) {
$term = get_term_by('slug', esc_attr($group), 'user-group');
$user_ids = get_objects_in_term($term->term_id, 'user-group');
foreach($user_ids as $user_id){
$fc_user = get_userdata($user_id);
if(! in_array($fc_user->user_email, $user_email) )
{
array_push($user_email, $fc_user->user_email);
}
}
}
foreach($to_excode as $codes) {
$value = explode('*',$codes)[1];
$users = get_users( array('meta_key' => 'programs' ) );
if($users){
foreach ($users as $index => $data) {
if(in_array($value , explode('#', $data->programs))){
if(! in_array($data->user_email, $user_email) )
{
array_push($user_email, $data->user_email);
}
}
}
}
}
}
foreach($user_email as $index => $email){
$to = $email;
$subject = $crm->vc_subject;
$body = $crm->post_content;
$headers = array(
'Content-Type: text/html; charset=UTF-8'
);
wp_mail($to, $subject, $body, $headers);
}
}
add_action( 'save_post', 'send_mail_to_user', 10, 2 );
我也尝试publish_post
了 hook ,创建新帖子时效果很好,但更新后效果相同。我也尝试过edit_post
并post_updated
挂钩,但我永远无法检索我的更新数据。
那么我该如何解决呢?哪个动作挂钩会给我所有的新数据?提前致谢。