I'm using have_fields to loop through an array and create a list of checkboxes. Everything seems to be working great, except that the checkboxes aren't consistently showing as "checked" on the backend. Here's the code I'm using:

<?php $items = array(
    ); ?>

    <?php while ($mb->have_fields('t_enabled_widgets', count($items))): ?>

        <?php $item = $items[$mb->get_the_index()]; ?>

        <input type="checkbox" name="<?php $mb->the_name(); ?>" value="<?php echo $item; ?>"<?php $mb->the_checkbox_state($item); ?>/> <?php echo ucwords(str_replace("-", " ", $item )); ?><br/>

    <?php endwhile; ?>

For example, when I check the first 4 boxes, (Bio, Youtube, Articles, and Learn More), all is well. When I check the 5th, it saves to the database, but when the page reloads, it's unchecked. This is obviously a problem because when you then "Update" the page again it's submitted as a blank value.

Any ideas?


After more searching I decided to try one of the alternative methods listed in the checkbox-meta.php example file. I used a "foreach" loop instead of the "while" loop and the checkbox state is now loading properly.

Here's the updated code:

<?php foreach ($items as $i => $item): ?>

    <?php $mb->the_field('t_enabled_widgets', WPALCHEMY_FIELD_HINT_CHECKBOX_MULTI); ?>

    <input type="checkbox" name="<?php $mb->the_name(); ?>" value="<?php echo $item; ?>"<?php $mb->the_checkbox_state($item); ?>/>
    <span><?php echo ucwords(str_replace("-", " ", $item )); ?></span>

<?php endforeach; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.