检查它是否是新的自定义帖子或使用save_post钩子进行更新

时间:2019-05-06 02:14:49

标签: php wordpress hook

我正在尝试使用wp_mail函数发送邮件并将其挂在save_post上。如果是新帖子还是刚刚更新帖子,如何检查?我尝试了save_post的update参数,但始终给我布尔型true的答案。如果发布后有新帖子,则只需发送。有可能吗?

这是我的代码:

add_action( 'save_post', 'dt_email_client_new', 13, 3 );
function dt_email_client_new( $post_id, $post, $update ) {

$post_type = get_post_type($post_id);

if($post_type != 'dt_appointments'){
    return;
}

if ( wp_is_post_revision( $post_id ) ) {
    return;
}

// Stop WP from clearing custom fields on autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    return;

// Prevent quick edit from clearing custom fields
if (defined('DOING_AJAX') && DOING_AJAX)
    return;

remove_action( 'save_post', 'dt_email_client_new', 13, 3 );//this will avoid duplicate emails

    //how can I check if its new post or update?
    $get_first_name = get_post_meta($post_id, 'first_name', true);
    $get_last_name = get_post_meta($post_id, 'last_name', true);
    $get_date_time = get_post_meta($post_id, 'appointment_date_time', true);
    $get_email = get_post_meta($post_id, 'email', true);
    $get_doctor_id = get_post_meta($post_id, 'doctor', true);
    $get_phone = get_post_meta($post_id, 'phone', true);

    $user_info = get_userdata( $get_doctor_id );
    $firstname = $user_info->first_name;
    $lastname = $user_info->last_name;

    $get_sched_date_format = date('F d, Y', strtotime($get_date_time));
    $get_sched_time_format = date('H:i A', strtotime($get_date_time));

    $to = $get_email;
    $headers = array('Content-Type: text/html; charset=UTF-8','From: Dentaltrends <sample@gmail.com>');
    $subject = 'sample subj here...';
    $body = '<p><strong>Hi '.$get_first_name.',</strong></p>
    <p style="margin: 0px;">Your appointment request has been confirmed. Please proceed to ......</p>
    <p></p>';

    wp_mail( $to, $subject, $body, $headers );

}

2 个答案:

答案 0 :(得分:0)

请尝试以下代码:

add_action('publish_post', 'send_admin_email');
function send_admin_email($post_id){

    $postdata = get_post($post_id);
    $time_differ = round(abs(strtotime($postdata->post_modified) - strtotime($postdata->post_date)) / 60,2);

    if ( $time_differ < 0.20 ) {
         wp_mail('test@gmail.com', 'Test', 'Test message');
    }
}

答案 1 :(得分:0)

您可以使用回调函数的第3个参数。干杯:)

add_action( 'save_post', 'my_save_post_function', 10, 3 );

function my_save_post_function( $post_ID, $post, $update ) {

if(!$update )
{
//new post
}
else
{
//update it
}


}