Optimize CPT-function with a loop
-
29-11-2019 - |
Question
I want to optimize my functions of a Custom Post Type (CPT). Now I have 10 meta boxes. For each box I have an extra function. The aim is to produce the 10 boxes in one function. I already tried the following code. The problem is that the entered values do not get saved.
function optimize() {
global $post;
$custom = get_post_custom($post->ID);
for ($i=0; $i<=9; $i++) {
$field_name[] = $custom['field_name'];
$checkbox_nr[] = $custom['checkbox_nr'];
echo 'Field Name '.($i).' <input name="field_name' . $i . '" value="' . $field_name[$i][0] . '" />';
}
update_post_meta($post->ID, "field_name1", $_POST["field_name1"]);
}
Solution
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 .' >';
}
}
?>