mardi 24 mai 2016

Retrieve checkbox values array

This is part of the form I've got in my functions.php file...

<?php foreach (get_categories() as $category) { ?>
    <input type="checkbox" value="<?php echo $category->cat_ID; ?>" name="allowed_categories[]" /><?php echo $category->name; ?>
<?php } ?>

...which gives me a list of all categories with checkboxes.

This handles saving it to the database when the form is submitted:

add_action( 'edit_user_profile_update', 'save_other_user_stuff' );

function save_other_user_stuff( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
    return false;
    update_user_meta( $user_id, 'allowed_categories', $_POST['allowed_categories'] );
}

When I submit the form it works fine, as in the checked values get stored in the database as expected. But there are two problems I can't seem to solve.

1) How can I mark the ones that were checked with "selected" (so that when I come back to my options page I can see which ones are currently selected).

...and...

2) How can I, on a separate page anywhere, retrieve a simple array of the checked values separated by commas. To clarify further, if in the form you checked 3 items and they had values 12, 36 and 40 respectively, then I'd like to show on a separate page: 12,36,40 (I plan to store that comma separated list of numbers as a variable to use in a different query, but that query is not part of this question).

Cheers.




Aucun commentaire:

Enregistrer un commentaire