Using the user profile hooks WordPress already has, KB Support provides additional hooks that ensure all custom user fields created by any KB Support extension are grouped together under a user profile page header section called KB Support.

There are two hooks of interest here;

The kbs_user_profile_fields filter is used to determine which custom user profile fields are registered within KBS and it is important to do this so that KBS knows whether or not to print out the KB Support profile page header section. It also ensures the hook required to display the profile fields is run.

Simply, if there are no custom fields registered within KBS, the KB Support profile page header section will not be displayed, and the kbs_display_user_profile_fields hook which displays custom KBS user fields will not run either.

/**
 * @param	array	$fields	Array of registed KBS custom user profile fields
 * @return	array	Filtered array of registed KBS custom user profile fields
 */
function mh_custom_profile_fields( $fields )	{

	$mh_fields = array( 'company_name' );
	$fields    = array_merge( $mh_fields, $fields );

	return $fields;

}
add_filter( 'kbs_user_profile_fields', 'mh_custom_profile_fields' );

In the above example, we’re registering the field name company_name.

Next up, we need to hook into the kbs_display_user_profile_fields action to display our field.

/**
 * @param	object	$user	The WP_User object
 * @return	void	Any output must be echo'd as `add_action` does not return a value
 */
function mh_company_name_profile_field( $user )	{

	ob_start();
	?>
	<tr>
		<th><label for="company_name"><?php _e( 'Company Name', 'kb-support' ); ?></label></th>

		<td><input type="text" name="company_name" id="company_name" class="regular-text" value="<?php echo esc_attr( get_the_author_meta( 'company_name', $user->ID ) ); ?>">

			<p class="description"><?php _e( 'Enter your company name here.', 'kb-support' ); ?></p>

		</td>
	</tr>
	<?php
	echo ob_get_clean();

}
add_action( 'show_user_profile', 'mh_company_name_profile_field' );
add_action( 'edit_user_profile', 'mh_company_name_profile_field' );

The above code will result in the following output:

Company Name

Remember, you’ll still need to hook into personal_options_update and edit_user_profile_update to save the value of your field(s) when the user saves changes.


Was this article helpful?