How to Save and Update Checkboxes for Repeatable Custom Fields

  php, wordpress

Currently, I am building custom metaboxes and custom fields into my WordPress theme. I am successfully able to save my text, select, URL and textarea for each repeatable field.

The issue I’m having are the checkboxes not saving after being checked. I am able to generate a checkbox in each repeatable custom field line when pressing "add". (After updating and refreshing the page the checkbox is there.) But then I check the checkbox, update and refresh. The box is there but is not checked.

I have looked for help for the last two weeks and still not having any success on saving these checkboxes. I’ve tried so many different strategies that I’ve found and either there is not a difference in saving or there is some kind of error. I am not an expert in PHP but I’v been learning on my own. Any help is greatly appreciated.

function addRepeatableFieldsCallback() {
  global $post;
  $repeatableFields = get_post_meta($post->ID, 'repeatableFields', true);
  wp_nonce_field( 'repeatableFieldsNonceAction', 'repeatableFieldsNonceField' ); ?>

Here is my table row:

<?php
if ( $repeatableFields ) :
foreach ( $repeatableFields as $field ) { ?>
  <tr>
    <td>
      <input type="checkbox" name="checkbox[]" id="checkbox[]" value="on" <?php checked( $field['checkbox'], 'on' ); ?> />
    </td>
    <td>
      <input type="text" name="checkDescription[]" value="<?php if($field['checkDescription'] != '') echo esc_attr( $field['checkDescription'] ); ?>" />
    </td>
  </tr>

Attempting to save:

add_action('save_post', 'saveRepeatableFieldsCallback');
function saveRepeatableFieldsCallback($post_id) {
  if ( ! isset( $_POST['repeatableFieldsNonceField'] ) ||
    ! wp_verify_nonce( $_POST['repeatableFieldsNonceField'], 'repeatableFieldsNonceAction' ) )
  return;

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

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

  $old = get_post_meta($post_id, 'repeatableFields', true);
  $new = array();
  $checkBoxes = $_POST['checkbox'];
  $checkDescription = $_POST['checkDescription'];
  $count = count( $checkDescription );

  for ( $i = 0; $i < $count; $i++ ) {

    if ( $checkDescription[$i] != '' ) :
    $new[$i]['checkDescription'] = stripslashes( strip_tags( $checkDescription[$i] ) );

    // WHAT GOES HERE FOR CHECKBOXES???

    endif;
  }

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

Source: Ask PHP

LEAVE A COMMENT