0

So i have been working on this legacy code and I'm trying to improve it a bit. I have this piece of code, which saves a bunch of custom fields from a post.

if(isset($_REQUEST['unidade-dir1-cargo'])){
    update_post_meta($post_id, 'unidade-dir1-cargo', sanitize_text_field($_POST['unidade-dir1-cargo']));
    update_post_meta($post_id, 'unidade-dir1-nome', sanitize_text_field($_POST['unidade-dir1-nome']));
    update_post_meta($post_id, 'unidade-dir1-email', sanitize_text_field($_POST['unidade-dir1-email']));
}
if(isset($_REQUEST['unidade-dir2-cargo'])){
    update_post_meta($post_id, 'unidade-dir2-cargo', sanitize_text_field($_POST['unidade-dir2-cargo']));
    update_post_meta($post_id, 'unidade-dir2-nome', sanitize_text_field($_POST['unidade-dir2-nome']));
    update_post_meta($post_id, 'unidade-dir2-email', sanitize_text_field($_POST['unidade-dir2-email']));
}
if(isset($_REQUEST['unidade-dir3-cargo'])){
    update_post_meta($post_id, 'unidade-dir3-cargo', sanitize_text_field($_POST['unidade-dir3-cargo']));
    update_post_meta($post_id, 'unidade-dir3-nome', sanitize_text_field($_POST['unidade-dir3-nome']));
    update_post_meta($post_id, 'unidade-dir3-email', sanitize_text_field($_POST['unidade-dir3-email']));
}
if(isset($_REQUEST['unidade-dir4-cargo'])){
    update_post_meta($post_id, 'unidade-dir4-cargo', sanitize_text_field($_POST['unidade-dir4-cargo']));
    update_post_meta($post_id, 'unidade-dir4-nome', sanitize_text_field($_POST['unidade-dir4-nome']));
    update_post_meta($post_id, 'unidade-dir4-email', sanitize_text_field($_POST['unidade-dir4-email']));
}
if(isset($_REQUEST['unidade-dir5-cargo'])){
    update_post_meta($post_id, 'unidade-dir5-cargo', sanitize_text_field($_POST['unidade-dir5-cargo']));
    update_post_meta($post_id, 'unidade-dir5-nome', sanitize_text_field($_POST['unidade-dir5-nome']));
    update_post_meta($post_id, 'unidade-dir5-email', sanitize_text_field($_POST['unidade-dir5-email']));
}

And it works. I've tried to change it into this, but it doest't work. Does anyone have an idea why?

$no_directors = 5;
$fields = array('cargo', 'nome', 'email');
for($i=1; $i<=$no_directors; $i++){
    foreach($fields as $field){
        $label = 'unidade-dir'.$i.'-'.$field;
        if(isset($_REQUEST[$label])){
            update_post_meta($post_id, $label, sanitize_text_field($_POST[$label]));
        }
    }
}
bfagundes
  • 95
  • 2
  • 4
  • 16

1 Answers1

1
 $no_directors = 5;
$fields = array('cargo', 'nome', 'email');
for($i=1; $i<=$no_directors; $i++){
    foreach($fields as $field){
        $label = "unidade-dir$i-$field";
        if(isset($_REQUEST[$label])){
            update_post_meta($post_id, $label, sanitize_text_field($_POST[$label]));
        }
    }
}
mujuonly
  • 11,370
  • 5
  • 45
  • 75