neilgee
12/15/2015 - 5:00 AM

WordPress Custom User Profile Fields

WordPress Custom User Profile Fields

<?php

//Ref - http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields

//to register the fields add in functions.php - example below uses filed called 'twitter' - add more in as required - this will show in the user profile in the dashboard

add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );

function my_show_extra_profile_fields( $user ) { ?>

	<h3>Extra profile information</h3>

	<table class="form-table">

		<tr>
			<th><label for="twitter">Twitter</label></th>

			<td>
				<input type="text" name="twitter" id="twitter" value="<?php echo esc_attr( get_the_author_meta( 'twitter', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Please enter your Twitter username.</span>
			</td>
		</tr>

	</table>
<?php }

//saving the custom fields - a further 2 actions are required to be able to save the field data

add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );

function my_save_extra_profile_fields( $user_id ) {

	if ( !current_user_can( 'edit_user', $user_id ) )
		return false;

	/* Copy and paste this line for additional fields. Make sure to change 'twitter' to the field ID. */
	update_usermeta( $user_id, 'twitter', $_POST['twitter'] );
}

//displaying the user data in the fron end
// the example below creates a html blovk which contains the data in a function - then that function can be displayed in a php template
// when building this use tehe function the_author_meta( $meta_key, $user_id ); - the meta key in this example being 'twitter'

function my_author_box() { ?>
	<div class="author-profile vcard">
		<?php echo get_avatar( get_the_author_meta( 'user_email' ), '96' ); ?>

		<h4 class="author-name fn n">Article written by <?php the_author_posts_link(); ?></h4>

		<p class="author-description author-bio">
			<?php the_author_meta( 'description' ); ?>
		</p>

		<?php if ( get_the_author_meta( 'twitter' ) ) { ?>
			<p class="twitter clear">
				<a href="http://twitter.com/<?php the_author_meta( 'twitter' ); ?>" title="Follow <?php the_author_meta( 'display_name' ); ?> on Twitter">Follow <?php the_author_meta( 'display_name' ); ?> on Twitter</a>
			</p>
		<?php } // End check for twitter ?>
	</div><?php
}

// you can use - the_author_meta() or get_the_author_meta() - the latter best used in a return
//and then add the function to a template

my_author_box();