WP - wp_create_user() inside transition_post_status hook

370 Views Asked by At

I have a situation where I need to create a new user every time a CPT post is created.

The CPT has the following fields that can be filled out upon post creation: $user_name, and $user_email

Here's what I'm trying, but it's not working:

function register_new_user( $new_status, $old_status, $post ) {
    if ( ( 'publish' === $new_status && 'publish' !== $old_status )
        && 'cpt' === $post->post_type
    ) {

        $user_name = get_post_meta($post_id, 'user_name', true);
        $user_email = get_post_meta($post_id, 'user_email', true);

        function wp_create_user( $username, $password, $email = '' ) {
                $user_login = wp_slash( $user_name );
                $user_email = wp_slash( $user_email );
                $user_pass  = $user_login;

                $userdata = compact( $user_login, $user_email, $user_pass );
                return wp_insert_user( $userdata );
        };
    };
};
add_action( 'transition_post_status', 'register_new_user', 10, 3 );

Any help with this is, as always, greatly appreciated.

2

There are 2 best solutions below

6
On

You can not re-declare a non-pluggable function register_new_user

function so61203170_create_new( $new_status, $old_status, $post ) {
    if ( ( 'publish' === $new_status && 'publish' !== $old_status )
        && 'cpt' === $post->post_type
    ) {
        $user_name = get_post_meta($post->ID, 'user_name', true);
        $user_email = get_post_meta($post->ID, 'user_email', true);

        // Password Will be Automatically Set as strong if left blank from array 
        // otherwise use 'user_pass' => $password
        $userdata = array(
            'user_login' => wp_slash( $user_name ),
            'user_email' => wp_slash( $user_email ),
            // Make Role Whatever You Want
            'role' => 'subscriber',
        );

        wp_insert_user($userdata);
    }
}
add_action( 'transition_post_status', 'so61203170_create_new', 10, 3 );
3
On

I modify your code and it's should work:

function register_new_user( $new_status, $old_status, $post ) {
    if ( ( 'publish' === $new_status && 'publish' !== $old_status )
        && 'cpt' === $post->post_type
    )
    {

        $user_name = get_post_meta( $post->ID, 'user_name', true );
        $user_email = get_post_meta( $post->ID, 'user_email', true );

        $user_login = wp_slash( $user_name );
        $user_email = wp_slash( $user_email );
        $user_pass  = wp_generate_password( 12 );

        $user_data = compact( $user_login, $user_email, $user_pass );
        return wp_insert_user( $user_data );
    }
    return null;
}

add_action( 'transition_post_status', 'register_new_user', 10, 3 );

You should getting errors, because you trying rewrite wordpress function.