1

我有一种情况,每次创建 CPT 帖子时我都需要创建一个新用户。

CPT 具有以下字段,可以在创建帖子时填写:$user_name$user_email

这是我正在尝试的,但它不起作用:

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

一如既往,非常感谢您对此的任何帮助。

4

2 回答 2

1

您不能重新声明不可插入的功能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 );
于 2020-04-14T10:24:57.347 回答
0

我修改了您的代码,它应该可以工作:

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

你应该得到错误,因为你试图重写 wordpress 功能。

于 2020-04-14T08:53:56.033 回答