【问题标题】:Check if its a new custom post or update using save_post hook检查它是新的自定义帖子还是使用 save_post 钩子更新
【发布时间】:2019-05-06 02:14:49
【问题描述】:

我正在尝试使用wp_mail 函数发送邮件并将其挂接到save_post。我如何检查它是新帖子还是只是更新帖子?我尝试了 save_post 的更新参数,但总是给我布尔值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: Test <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 );

}

【问题讨论】:

标签: php wordpress hook


【解决方案1】:

请尝试以下代码:

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');
    }
}

【讨论】:

    【解决方案2】:

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

    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
    }
    
    
    }
    

    【讨论】:

    • 关于 $update 始终为 true 的信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2020-11-02
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多