Add Category Checkboxes to User Profile

by Edegist   Last Updated July 11, 2019 18:08 PM

I am trying to add category selection checkboxes to the user profile, and other pages, so a user can select a few categories and hit save and the categories will be saved to an array in the user meta.

I have found THIS ANSWER (from years ago) that seems to do what I want, except it doesn't fully work.

The Problem:

The code seems to work fine on the back-end on the user profile page, however, I tried putting the code on a page with a shortcode, and all it does is display the categories. It doesn't load the previously saved categories, even though the user is logged in and has saved some categories.

Here is the code:

//create the user category fields
add_action( 'show_user_profile', 'add_user_categories' );
add_action( 'edit_user_profile', 'add_user_categories' );
add_shortcode( 'user_categories', 'add_user_categories' );

function add_user_categories($user ){
    ?>
    <table class="form-table">
    <tr>
        <th><label for="user_categories"><?php _e("User categories"); ?></label></th>
        <td>
            <?php
                $data = get_the_author_meta( 'user_categories', $user->ID );
                $args = array( 'hide_empty' =>0, 'taxonomy'=> 'category');
                $categories=  get_categories($args);
                if ($categories){
                    foreach ( $categories as $category ){ 
                        if(in_array($category->term_id,(array)$data)) {
                            $selected = 'checked="checked""';
                        } else {
                            $selected = '';
                        }
                        echo '<input name="user_categories[]" value="'.$category->term_id.'" '.$selected.' type="checkbox"/>'.$category->name.'<br/>';
                    }
                }
            ?>
        </td>
    </tr>
    </table>
    <?php
}

//save the user category fields 
add_action( 'personal_options_update', 'save_user_categories' );
add_action( 'edit_user_profile_update', 'save_user_categories' );

function save_user_categories( $user_id ){
    if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
    update_usermeta( $user_id, 'user_categories', $_POST['user_categories'] );
}

I would really appreciate if someone can steer me in the right direction! Thanks in advance!



Related Questions


Updated June 03, 2017 08:08 AM

Updated February 11, 2018 08:08 AM

Updated August 31, 2017 12:08 PM

Updated June 03, 2017 20:08 PM

Updated July 13, 2019 00:08 AM