首先,您需要创建以下函数:
function checkEmailAlreadyExists( $message_id ) {
$posts_with_meta = get_posts( array(
\'posts_per_page\' => 1, // we only want to check if any exists, so don\'t need to get all of them
\'post_type\' => \'my-custom-post-type\',
\'meta_key\' => \'ticket_id\',
\'meta_value\' => $message_id,
\'fields\' => \'ids\', // we don\'t need it\'s content, etc.
) );
return ( count( $posts_with_meta ) ) ? true : false;
}
现在,您只需将其添加到当前代码中:
$total = $emails->total_msg();
for ( $j=1; $j <= $total; $j++ ) {
$mail = $emails->get( $j );
if ( !empty( $mail[\'header\']->message_id ) && !checkEmailAlreadyExists( $mail[\'header\']->message_id ) ) {
$post_array = array(
\'post_content\' => $mail[\'body\'],
\'post_title\' => $mail[\'header\']->subject,
\'post_type\' => \'my-custom-post-type\',
\'post_status\' => \'publish\',
\'meta_input\' => array(
\'from\' => $mail[\'header\']->fromaddress,
\'email_date\' => $mail[\'header\']->Date,
\'ticket_id\' => $mail[\'header\']->message_id,
),
);
wp_insert_post( $post_array );
}
}