You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WordPress自定义文章标题设置为用户的first_name last_name格式

解决方案

你可以直接调用 WordPress 用户对象内置的姓氏(last_name)、名字(first_name)字段拼接文章标题,同时手动指定post_name参数来实现你要的别名格式,另外原代码里的角色判断逻辑也可以优化得更稳妥,修改后的完整代码如下:

add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );

function wpse_216921_company_cpt( $user_id )
{
    // 获取用户信息
    $user_info = get_userdata( $user_id );
    $user_roles = $user_info->roles;

    // 优化角色判断:直接检查角色数组,避免多角色场景下判断失效
    if ( in_array( 'author', $user_roles ) ) {
        // 拼接姓名作为文章标题
        $full_name = $user_info->first_name . ' ' . $user_info->last_name;
        // 兜底逻辑:如果用户未填写姓/名, fallback 用昵称
        if(trim($full_name) == '') $full_name = $user_info->nickname;
        // 生成slug:转小写+空格替换为点
        $post_slug = strtolower(str_replace(' ', '.', $full_name));

        // 构建文章参数
        $user_post = array(
            'post_title'   => $full_name,
            'post_name'    => $post_slug, // 手动指定别名
            'post_status'  => 'publish',
            'post_type'    => 'athlete',
            'post_author'  => $user_info->ID
        );
        // 插入文章到数据库
        $post_id = wp_insert_post( $user_post );
    }
}

注意事项

  • 请确认你注册athlete自定义文章类型时,已经开启了rewrite配置,设置slug为athlete,这样最终的前端访问路径才会是athlete/john.smith格式
  • 如果你的站点要求用户注册时必须填写姓名,那可以删除上面的兜底逻辑

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:15:02