查看该电子邮件是否存在

时间:2021-12-15 作者:Rohit kc

我使用PHP IMAP连接提取了一组电子邮件,并将这些电子邮件分配给自定义的帖子类型。下面是我如何将这些电子邮件分配到自定义帖子类型的代码。

    $total =  $emails->total_msg(); 
    for ($j=1; $j <= $total; $j++) { 
       $mail =  $emails->get($j);
       $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,   // add post meta as many as you want
            \'ticket_id\' => $mail[\'header\']->message_id,
            ),
       );
       wp_insert_post($post_array);
    }
现在,$emails 是我存放所有电子邮件的地方。我想做一个简单的检查,如果电子邮件已经存在,不要做wp_insert_post() 如果电子邮件不存在,则只需wp_insert_post.我不太懂逻辑和怎么做。如果有人能做到。这将是一个很大的帮助。

1 个回复
最合适的回答,由SO网友:FS-GSW 整理而成

首先,您需要创建以下函数:

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

相关推荐

搜索格式.php覆盖不起作用

我正在上Udemy课程,学习如何制作Wordpress插件和主题。我正在观看的视频让我通过searchform用一个自定义的搜索小部件覆盖默认的搜索小部件。php。根据我收集的信息,只要我遵循以下步骤,该文件应自动加载主题的其余部分:/主题目录/功能。php/* Some other code */ include ( get_theme_file_path(\'/includes/widgets.php\') ); add_action("widgets_init",