在Wordpress中,我正在尝试在特定用户角色“作者”的新用户注册表上创建自定义帖子
为此我试着在Function.php中找出这个代码
add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles=$user_info->roles;
if ($user_roles == 'author') {
// Create a new post
$user_post = array(
'post_title' => $user_info->nickname,
'post_type' => 'CustomPost', // <- change to your cpt
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
但不成功。添加上面的代码后没有错误工作正常但它不会触发自动而不创建新的自定义帖子
我很简单,每当我添加新的作者/新作者注册时,它都会创建一个自定义帖子,其标题与用户名相同。并发布它
答案 0 :(得分:1)
您正在检查的角色不正确,$user_info->roles
返回一个数组,而不是字符串。找到下面修改后的代码,
add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
if ($this_user_role == 'author') {
// Create a new post
$user_post = array(
'post_title' => $user_info->nickname,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'CustomPost', // <- change to your cpt
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
希望这有帮助。