| 1 | function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array() ) { |
|---|
| 2 | $email_address = sanitize_email( $email_address ); |
|---|
| 3 | $action_name = sanitize_key( $action_name ); |
|---|
| 4 | |
|---|
| 5 | if ( ! is_email( $email_address ) ) { |
|---|
| 6 | return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) ); |
|---|
| 7 | } |
|---|
| 8 | |
|---|
| 9 | if ( ! $action_name ) { |
|---|
| 10 | return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) ); |
|---|
| 11 | } |
|---|
| 12 | |
|---|
| 13 | $user = get_user_by( 'email', $email_address ); |
|---|
| 14 | $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0; |
|---|
| 15 | |
|---|
| 16 | // Check for duplicates. |
|---|
| 17 | $requests_query = new WP_Query( array( |
|---|
| 18 | 'post_type' => 'user_request', |
|---|
| 19 | 'post_name__in' => array( $action_name ), // Action name stored in post_name column. |
|---|
| 20 | 'title' => $email_address, // Email address stored in post_title column. |
|---|
| 21 | - 'post_status' => 'any', |
|---|
| 22 | + 'post_status' => array('request-pending', 'request-confirmed'), |
|---|
| 23 | 'fields' => 'ids', |
|---|
| 24 | ) ); |
|---|
| 25 | |
|---|
| 26 | if ( $requests_query->found_posts ) { |
|---|
| 27 | return new WP_Error( 'duplicate_request', __( 'A request for this email address already exists.' ) ); |
|---|
| 28 | } |
|---|
| 29 | |
|---|
| 30 | $request_id = wp_insert_post( array( |
|---|
| 31 | 'post_author' => $user_id, |
|---|
| 32 | 'post_name' => $action_name, |
|---|
| 33 | 'post_title' => $email_address, |
|---|
| 34 | 'post_content' => wp_json_encode( $request_data ), |
|---|
| 35 | 'post_status' => 'request-pending', |
|---|
| 36 | 'post_type' => 'user_request', |
|---|
| 37 | 'post_date' => current_time( 'mysql', false ), |
|---|
| 38 | 'post_date_gmt' => current_time( 'mysql', true ), |
|---|
| 39 | ), true ); |
|---|
| 40 | |
|---|
| 41 | return $request_id; |
|---|
| 42 | } |
|---|