如何在WordPress作者页展示可在用户资料编辑的带WYSIWYG编辑器的额外文本字段
实现WordPress作者页带WYSIWYG编辑器的自定义字段方案
步骤1:添加带可视化编辑器的自定义字段到用户资料页
将以下代码添加到当前主题的functions.php文件,或自定义功能插件的主文件中:
// 在用户资料页添加WYSIWYG自定义字段 add_action( 'show_user_profile', 'add_extra_author_editor_field' ); add_action( 'edit_user_profile', 'add_extra_author_editor_field' ); function add_extra_author_editor_field( $user ) { ?> <h3>额外作者信息</h3> <table class="form-table"> <tr> <th><label for="custom_author_bio_extra">作者补充介绍</label></th> <td> <?php $content = get_user_meta( $user->ID, 'custom_author_bio_extra', true ); wp_editor( $content, 'custom_author_bio_extra', array( 'textarea_rows' => 10 ) ); ?> </td> </tr> </table> <?php } // 保存自定义字段内容 add_action( 'personal_options_update', 'save_extra_author_editor_field' ); add_action( 'edit_user_profile_update', 'save_extra_author_editor_field' ); function save_extra_author_editor_field( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } if ( isset( $_POST['custom_author_bio_extra'] ) ) { update_user_meta( $user_id, 'custom_author_bio_extra', wp_kses_post( $_POST['custom_author_bio_extra'] ) ); } }
添加完成后,登录后台进入用户资料编辑页,就能看到带完整WYSIWYG功能的自定义输入字段。
步骤2:在作者页面展示字段内容
找到主题的作者页模板(通常命名为author.php,如果不存在可以复制archive.php重命名为author.php使用),在你需要展示该字段的位置插入以下代码:
// 获取并输出作者自定义字段内容 $current_author = get_queried_object(); $extra_author_content = get_user_meta( $current_author->ID, 'custom_author_bio_extra', true ); if ( $extra_author_content ) { echo '<div class="author-extra-content">'; echo wp_kses_post( $extra_author_content ); echo '</div>'; }
你可以自行给外层author-extra-content类添加CSS样式,匹配你的主题设计。
注意事项
- 避免主题更新覆盖修改,建议将功能代码放到子主题的
functions.php文件中,或封装为独立的自定义功能插件 - 示例中使用的字段名
custom_author_bio_extra、字段标题作者补充介绍都可以自行修改,只需保证添加字段、保存字段、展示字段三处的字段名保持一致即可 - 若需要限制仅特定角色可编辑该字段,可在保存逻辑中添加用户角色判断条件
内容的提问来源于stack exchange,提问作者johny
相关产品推荐
相关产品推荐

