简体   繁体   中英

PHP, mark checkboxes as checked from database array

I have scoured the net trying to find my exact solution and cannot find anything relevant to my situation. I need to save 2 different checkboxes as a single array to Wordpress as custom post meta. I can make this part work, what I am having trouble with is marking the checkboxes as checked if they exist in the array. I have not included the surrounding meta box code, just the portions relevant to my issue.

Here how I am trying to display the checked boxes (this is not working):

<?php $AMP = get_post_meta($post->ID, 'bta_propertyAMP'); ?>
<input type="checkbox" class="regular-text" name="bta_propertyAMP[]" value="30" <?php echo (in_array('30', $AMP)) ? 'checked="checked"' : ''; ?> /> 30 AMP
<input type="checkbox" class="regular-text" name="bta_propertyAMP[]" value="50" <?php echo (in_array('50', $AMP)) ? 'checked="checked"' : ''; ?> /> 50 AMP

Here is how I am saving this (this part is working):

<?php 
$old = get_post_meta($post_id, 'bta_propertyAMP', true);
$new = array();
$amps = $_POST['bta_propertyAMP'];
$count = count( $amps );

for ( $i = 0; $i < $count; $i++ ) {
 if ( $amps[$i] != '' ) :
   $new[$i]['bta_propertyAMP'] = stripslashes( strip_tags( $amps[$i] ) );
 endif;
}

if ( !empty( $new ) && $new != $old ) {
  update_post_meta( $post_id, 'bta_propertyAMP', $new );
} elseif ( empty($new) && $old ) {
  delete_post_meta( $post_id, 'bta_propertyAMP', $old );
}
?>

The conditional in your second AMP checkbox is also checking for

in_array('30', $AMP)

When you probably meant to have it check for 50:

in_array('50', $AMP)

It looks like you actually just need to replace them with

in_array('30', $AMP[0])

and

in_array('50', $AMP[1])

Sorry I'm now on mobile - you may need to remove the single quotes around the 30 and the 50, but the array pointers in the square brackets are what you need, since your meta value is an array of arrays (hence why the loop worked)

Ok I finally got this working, there is probably a better way but this does work if anyone else runs into this. I looped through the array and created a variable for each checkbox that I could then check outside the loop if it was true.

<?php 
$amps = get_post_meta($post->ID, 'bta_propertyAMP', true);
  foreach($amps as $amp) :
    if($amp['bta_propertyAMP'] == 30) { $amp30 = '1'; }
    if($amp['bta_propertyAMP'] == 50) { $amp50 = '1'; }
endforeach; 
?>
<input type="checkbox" class="regular-text" name="bta_propertyAMP[]" value="30" <?php echo ($amp30 == 1) ? 'checked="checked"' : ''; ?> /> 30 AMP
<input type="checkbox" class="regular-text" name="bta_propertyAMP[]" value="50" <?php echo ($amp50 == 1) ? 'checked="checked"' : ''; ?> /> 50 AMP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM