在插入新用户时,我想在Wordpress中添加一个自定义的帖子类型(称为pullow)。这个wp_insert_user()
用于创建新用户。
我有以下代码:
function register_user_pupil($user_id) {
//Count nr of occurences in user-table for submitted email-adress
$email_form = $_POST[\'email\'];
$sql = "SELECT * FROM $wpdb->users";
$sql .= " WHERE user_email = \'%s\'";
$count_users_email = intval($wpdb->get_var($wpdb->prepare( $sql, $email)));
//Check if email (from exists) already exists in the system (in users table)
//If it doesn\'t, create new user into variable. If it does, store that user in variable
//based on email-adress
if ($count_users_email === 0) {
$current_user = new WP_User($user_id);
}
else {
$current_user = get_user_by( \'email\', $email_form );
}
//Create a new pupil custom post-type for this user
$user_registration_post = array(
\'post_title\' => $current_user->display_name,
\'post_type\' => \'pupil\',
\'post_status\' => \'draft\', //This registration cpt is not available for public
\'post_author\' => $current_user->ID
);
$postid_pupil = wp_insert_post( $user_registration_post );
//postid should return something above 0 and not a WP_Error-object
if (is_array($postid_pupil) || intval($postid_pupil) === 0) {
throw new Exception(\'Kan inte skapa en elev-registrering\');
}
//Rest of updating is done by function postsubmit() (saving the pupil CPT)
}
//Hook for handling new users
add_action( \'user_register\', \'register_user_pupil\', 10, 3 );
问题是调用此函数
AFTER 用户已插入,我希望执行它
BEFORE 插入实际用户。我还尝试使用register\\u post挂钩,但在插入用户之前,不会调用此代码。我也试着弄清楚我是否可以用钩子
pre_{something}
, 但是没有运气。
有人能帮我吗?非常感谢:-)
最合适的回答,由SO网友:s_ha_dum 整理而成
我想你让这件事变得更加困难了。
在上运行代码user_register
和update_profile
检查帖子是否存在,如果不存在则创建帖子。WordPress应该负责剩下的事情类似于:
function register_user_pupil($user_id) {
$current_user = new WP_User($user_id);
$post_args = array(
\'post_title\' => $current_user->data->display_name,
\'post_type\' => \'pupil\',
\'post_status\' => \'draft\', //This registration cpt is not available for public
\'post_author\' => $current_user->ID
);
$exists = new WP_Query($args);
if (!$exists->have_posts()) {
$postid_pupil = wp_insert_post( $post_args );
}
//postid should return something above 0 and not a WP_Error-object
if (is_array($postid_pupil) || intval($postid_pupil) === 0) {
throw new Exception(\'Kan inte skapa en elev-registrering\');
}
//Rest of updating is done by function postsubmit() (saving the pupil CPT)
}
add_action( \'profile_update\', \'register_user_pupil\');
add_action( \'user_register\', \'register_user_pupil\');
我没有你的CPT和支持代码,所以我不能真正测试它,但我很确定它很接近。
WordPress将强制使用唯一的电子邮件地址,所以我不认为有必要担心这一点。