Creating and working with custom built fields in a WordPress author’s profile can add whole new worlds of functionality to a blog. For example, today I’m going to show you how to create a field in your profile page that will allow authors to submit their own Adsense code so that they can display their own ads on any articles that they write.

It’s as simple as creating the field and then fetching it to use in your theme.

First, we’re going to add an extra text box to the profile page. You can do this by pasting the following code into your theme’s functions.php.

Note: In our example, we’re creating a field where users can submit their personal adsense code. If you want to use this concept for some other purpose then simply replace each instance of “adsense_336” with the name of your desired field and replace the description with something that accurately describes your custom field.

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>Revenue Sharing: Adsense Information</h3>

 <table class="form-table">

  <tr>
   <th><label for="adsense_336">Adsense 336x280</label></th>

   <td>
    <textarea type="text" rows="10" cols="60" name="adsense_336" id="adsense_336" value="<?php echo esc_attr( get_the_author_meta( 'adsense_336', $user->ID ) ); ?>" class="regular-text" ></textarea><br />
    <span class="description">If you provide your code for a 336x280 adsense ad, we'll use your advertisements on your posts.</span>
   </td>
  </tr>

 </table>
<?php }

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, 'adsense_336', $_POST['adsense_336'] );
}

Paste the following code into your theme’s single.php as this will allow you to call and display the field that you’ve created.

Note: In our example, I’ve created an area for you to place the house’s ads so that you have something to display when a user doesn’t have personalized ad code applied to their profile.

<?php if(get_the_author_meta('adsense_336')=='') : ?>
  <!-- Insert Default Google Adsense Here -->

  <!-- End Default Google Adsense Here -->
<?php else: the_author_meta('adsense_336'); endif; ?>

So there you have it. What other ways can you think of that would be useful to use this concept?

Nicholas Cardot

About Nicholas Cardot

It's my personal quest to enable every person that I can to unlock that dormant potential concerning their online influence. Also, I'm a geek.

14 Comments

Leave a Reply