Custom Fields
Re-Envisioned
Support MB Custom Post Type Check data before saving

This topic contains 1 reply, has 2 voices, and was last updated by  Anh Tran 2 months, 1 week ago.

  • Creator
    Topic
  • #13264
    Resolved
    netalys
    Participant

    Hi, I think I’m not so far but I can’t figure it out…
    I have created a CPT named “Client” with an email field.
    When I add a new client, I save it and automatically it creates a WP user with his email address. I know how to create it, and I know how to check if email already exist in WP users.
    What I’m not able to do is :
    – Do NOT save the post if email already exist
    – Go back to post and display an error notice in that case saying “Email already exist”

    Here is my code :

    function my_add_user_client($post_id)
    {
        $email = rwmb_get_value( 'email_contact', $post_id );
        $password = rwmb_get_value( 'password_contact', $post_id );
    
        $verif_mail = email_exists( $email );
    
        if($verif_mail){
            //Don't save, go back and display a notice with an error
        }else{
            $user_id = wp_create_user( $email, $password, $email );
            $user_id_role = new WP_User($user_id);
            $user_id_role->set_role('contributor');
        }
    
    }
    
    add_action('save_post_client', 'my_add_user_client', 20 );

    Thanks for your help !

Viewing 1 replies (of 1 total)
  • Author
    Replies
  • #13285

    Anh Tran
    Keymaster

    I’m not aware of any method that can stop WordPress from saving post. I found a good discussion on this topic that might be useful in this case.

Viewing 1 replies (of 1 total)

You must be logged in to reply to this topic.