试图在CustomPostType发布时创建用户,我尝试了以下操作,但不起作用。
function adduseronpostpublish( $new_status, $old_status, $post )
{
if ( \'publish\' !== $new_status or \'publish\' === $old_status
or \'custompostype\' !== get_post_type( $post ) )
return;
function add_new_user_account(){
$username = \'test\'; //username
$password = \'test\'; //password
$email = "[email protected]"; //email
if ( !username_exists( $username ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $username, $password, $email );
$user = new WP_User( $user_id );
$user->set_role( \'contributor\' ); //either of \'administrator\', \'subscriber\', \'editor\', \'author\', \'contributor\'
}
}
add_action(\'init\',\'add_new_user_account\');
}
}
add_action( \'transition_post_status\', \'adduseronpostpublish\', 10, 3 );
最合适的回答,由SO网友:denis.stoyanov 整理而成
请尝试以下代码:
add_action( \'transition_post_status\', \'wpse_206193_new_user_from_custom_post\', 10, 3 );
function wpse_206193_new_user_from_custom_post( $new_status, $old_status, $post )
{
if ( \'publish\' !== $new_status or \'publish\' === $old_status
or \'my_custom_post\' !== get_post_type( $post ) )
return;
$userdata = array(
\'user_login\' => \'user_name\',
\'user_email\' => \'[email protected]\',
\'user_pass\' => NULL,
\'role\' => \'contributor\'
);
if ( !username_exists( $userdata[\'user_login\'] ) && !email_exists( $userdata[\'user_email\'] ) ) {
wp_insert_user($userdata);
}
}
你不需要开枪
wp_create_user
在…上
init
或者在函数中使用单独的函数。