从帖子类型创建新帖子时发送电子邮件通知

时间:2019-07-15 04:06:12

标签: wordpress

我正在尝试使它起作用,我觉得我已经尝试了从transition_post_statuswp_insert_post甚至draft_to_pending的所有操作。

我正在尝试向用户和帖子作者发送电子邮件。通过ACF用户对象设置用户。我认为的问题是,可能元数据不可用或某些原因,因为$ author和$ user不是对象,因此无法通过ID查找它们并获取其数据。

这是我的功能:

add_action( 'transition_post_status', 'send_volunteer_request_email', 10, 3 );
function send_volunteer_request_email( $new_status, $old_status, $post ){
  if ( 'volunteers' !== get_post_type( $post ) )
    return;

  if( wp_is_post_autosave( $post ) ) return;

  $user = get_field('user', $post);
  $user_data = get_userdata( $user );
  $the_event = get_field('event', $post);
  $event = get_post($the_event);
  $eventLink = get_permalink($event);
  $author = get_userdata( $event->post_author );

  if(get_post_status($post) == 'pending'){
    //Notify event author
    $headers = array('Content-Type: text/html; charset=UTF-8');
    $subject = 'You have a new volunteer';
    $body = '<p>A member has volunteered to meet your need. Click <a href="' . $eventLink . '">here</a> to view and accept or decline!</p>';
    $body .= '<p>Thank you for being a valuable member<br><a href="https://www.google.com">https://www.goole.com</a><br>910-555-1234</p>';
    wp_mail( $author->user_email, $subject, $body, $headers );
  }
}

以下是其中一个错误的示例:

PHP Notice:  Trying to get property 'user_email' of non-object

最后,您可以看到这些位置 enter image description here

1 个答案:

答案 0 :(得分:0)

尝试如下更改代码:

$user = get_field('user', $post->ID);
$user_data = get_userdata( $user );
$the_event = get_field('event', $post->ID);
$event = get_post($the_event);

出现错误的原因是因为您是将post对象传递给get_field函数而不是post id。