How to add/save Custom Field in user settings/profile “Checkbox list”

Justin Tadlock has a good tutorial to get you started:

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

There are some specifics to dealing with checkboxes however, and some custom code if you want to make checkboxes that correspond to tags/categories.

To generate the form fields and save the data use the following snippet:

<?php

function user_interests_fields( $user ) {
    // get product categories
    $tags = get_terms('post_tag', array('hide_empty' => false));
    $user_tags = get_the_author_meta( 'user_interests', $user->ID );
    ?>
    <table class="form-table">
        <tr>
            <th>My interests:</th>
            <td>
        <?php
        if ( count( $tags ) ) {
            foreach( $tags as $tag ) { ?>
            <p><label for="user_interests_<?php echo esc_attr( $tag->slug); ?>">
                <input
                    id="user_interests_<?php echo esc_attr( $tag->slug); ?>"
                    name="user_interests[<?php echo esc_attr( $tag->term_id ); ?>]"
                    type="checkbox"
                    value="<?php echo esc_attr( $tag->term_id ); ?>"
                    <?php if ( in_array( $tag->term_id, $user_tags ) ) echo ' checked="checked"'; ?> />
                <?php echo esc_html($tag->name); ?>
            </label></p><?php
            }
        } ?>
            </td>
        </tr>
    </table>
    <?php
}
add_action( 'show_user_profile', 'user_interests_fields' );
add_action( 'edit_user_profile', 'user_interests_fields' );

    // store interests
    function user_interests_fields_save( $user_id ) {
        if ( !current_user_can( 'edit_user', $user_id ) )
            return false;
        update_user_meta( $user_id, 'user_interests', $_POST['user_interests'] );
    }
    add_action( 'personal_options_update', 'user_interests_fields_save' );
    add_action( 'edit_user_profile_update', 'user_interests_fields_save' );

?>

You can then call the get_the_author_meta() function to get at your array of tag IDs which can then be used in a query eg:

query_posts( array( 'tag_id' => get_the_author_meta( 'user_interests', $user_id ) ) );

Leave a Comment