How to save multiple checkboxes in WordPress custom post type

I currently have a custom post type with a meta box. Within that meta box is a few checkboxes “tag1” and “tag2”. For some reason I can not get both of the checkboxes to save. I can save one of them, but not both. Can anyone steer me in the right direction? I’m thinking I have to incorporate in_array() in lines 8 & 11 but not all that sure. Any help is appreciated, thanks!

What I’m working with:

// set a variable so we can append it to each row
$i = 1;

foreach ( $repeatable_fields as $field ) { ?>
  <label for="_tests[<?php echo $i;?>][test_tag][tag1]">
    <input type="checkbox" id="_tests[<?php echo $i;?>][test_tag][tag1]" name="_tests[<?php echo $i;?>][test_tag]" value="tag1" <?php checked( $field['test_tag'], 'tag1' ); ?> />tag1
  </label>
  <label for="_tests[<?php echo $i;?>][test_tag][tag2]">
    <input type="checkbox" id="_tests[<?php echo $i;?>][test_tag][tag2]" name="_tests[<?php echo $i;?>][test_tag]" value="tag2" <?php checked( $field['test_tag'], 'tag2' ); ?> />tag2
  </label>

<?php $i++; } ?>

<?php

  add_action('save_post', 'hhs_repeatable_meta_box_save', 10, 2);
  function hhs_repeatable_meta_box_save($post_id) {

  if ( ! isset( $_POST['hhs_repeatable_meta_box_nonce'] ) ||
  !wp_verify_nonce( $_POST['hhs_repeatable_meta_box_nonce'], 'hhs_repeatable_meta_box_nonce' ) )
  return;

  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
  return;

  if (!current_user_can('edit_post', $post_id))
  return;

  $clean = array();

  if  ( isset ( $_POST['_tests'] ) && is_array( $_POST['_tests'] ) ) :

      foreach ( $_POST['_tests'] as $i => $test ){

      // skip the hidden "to copy" div
      if( $i == '%s' ){
          continue;
      }

  $test_tags = array ( 'tag1', 'tag2' );

      $clean[] = array(
          'test_tag' => isset( $test['test_tag'] ) && in_array( $test['test_tag'], $test_tags ) ? $test['test_tag'] : null,
          );

  }

  endif;

  // save test data
  if ( ! empty( $clean ) ) {
      update_post_meta( $post_id, 'repeatable_fields', $clean );
  } else
      delete_post_meta( $post_id, 'repeatable_fields' );
  }

Related posts

1 comment

  1. Your checkboxes have the same name _tests[<?php echo $i;?>][test_tag], you should put [] after it and you can receive the values like an array.

Comments are closed.