Optimize CPT-function with a loop

Finally I got the solution. One of the major problems was the usage of “get_post_custom” for fetching the database. I used “get_post_meta” instead and it was a lot easier to work with the array that was created by that function. I am sure that it would have been possible to do it with the first function as wee but I do not really understand its characteristics. For further understanding i recommend this explenation: What is the index [0] for on post meta fields?

It was kind of tricky to integrate the checkboxes into the loop. First I just assigned empty brackets to the name of the checkboxes:

<?php echo '<input type="checkbox" name="checkbox_nr[]"'. $is_checked .' >';?>

This causes the problem that the the array includes only the checkboxes that are checked. For example: You check checkbox No. 1, 3 and 4 but not the second one. PHP ignores the unchecked box and assigns the second key to the third box. This causes wrong checked boxes after submitting.

The solution is this:

<?php echo '<input type="checkbox" name="checkbox_nr[' .$i.']"'. $is_checked .' >';?>

So, here is the function as a whole:

<?php function optimize() {
        global $post;
        $field_name = get_post_meta($post->ID, 'field_name', TRUE);
        $checkbox_nr = get_post_meta($post->ID, 'checkbox_nr', TRUE);
              for ($i=0; $i<=10; $i++) {                     
                echo 'Field Name <input name="field_name[]" value="' .  $field_name[$i] . '" /><br />';            
                if (isset($checkbox_nr[$i]))
                  //fetch all checked Checkboxes and verify if they are checked or not
                {
                  $is_checked = 'checked=\"checked\"';
                }
                else {
                  $is_checked = '';
                }

            echo '<input type="checkbox" name="checkbox_nr[' .$i.']"'. $is_checked .' >';

               }

           }
            ?>