O
O
OneTwoThreeFourFive2018-09-26 14:24:32
WordPress
OneTwoThreeFourFive, 2018-09-26 14:24:32

Is it possible to save post meta wordpress like this?

Hello. There are additional fields for posts. Similar to these:

<input type="text" name="custom-field[0][field-type-0] value="value" />
<input type="text" name="custom-field[1][field-type-0] value="value" />

<input type="text" name="custom-field[2][field-type-1] value="value" />
<input type="text" name="custom-field[3][field-type-1] value="value" />

To save, I use the following function:
function custom_field_save( $post_id ) {
  if ( !isset($_POST['custom_field_nonce']) || !wp_verify_nonce($_POST['custom_field_nonce'], plugin_basename( __FILE__ ) ) ) return false;
  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE  ) return false;
  if ( !current_user_can('edit_post', $post_id) ) return false;
  if( !isset($_POST['custom-field']) ) {
    delete_post_meta($post_id, 'custom-field');
  } else {
    update_post_meta($post_id, 'custom-field', $_POST['custom-field']);
  }
}
add_action( 'save_post', 'custom_field_save' );

The database is written:
array(4) {
  [0]=>
  array(1) {
    ["field-type-0"]=>
    string(5) "value"
  }
  [1]=>
  array(1) {
    ["field-type-0"]=>
   string(5) "value"
  }
  [2]=>
  array(1) {
    ["field-type-1"]=>
    string(5) "value"
  }
  [3]=>
  array(1) {
    ["field-type-1"]=>
    string(5) "value"
  }
}

Is it possible to save like this or do I need to use foreach to save?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2018-09-26
@pton

I think you can
But "delete_post_meta" is superfluous
But it's better to read here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question