From cb2ccd64df46f23db8f6cf23596ade160d151117 Mon Sep 17 00:00:00 2001 From: Darko Gjorgjijoski Date: Sun, 27 Mar 2022 07:47:34 +0000 Subject: [PATCH] Add save_mode for metaboxes The save mode tells how the metabox values are stored in the databse\n If you set save_mode=compact then the values of the metabox are stored in an array instead of single value. --- src/Metabox.php | 58 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/src/Metabox.php b/src/Metabox.php index a666a8c..8089039 100644 --- a/src/Metabox.php +++ b/src/Metabox.php @@ -81,6 +81,40 @@ function ( $classes ) { } } + + /** + * Returns the field value + * + * @param $post + * @param $field + * + * @return string + * + * @since 1.0.4 + */ + public function get_field_value( $post, $field ) { + + $save_mode = $this->get_field_save_mode(); + + if ( 'default' === $save_mode ) { + return get_post_meta( $post->ID, $field['id'], true ); + } else { + $data = get_post_meta( $post->ID, $this->meta_box['id'], true ); + + return isset( $data[ $field['id'] ] ) ? $data[ $field['id'] ] : ''; + } + + } + + /** + * Returns the save mode + * @return mixed|string + * @since 1.0.4 + */ + public function get_field_save_mode() { + return isset($this->meta_box['save_mode']) ? $this->meta_box['save_mode'] : 'default'; + } + /** * Meta box view. * @@ -109,7 +143,7 @@ public function build_meta_box( $post, $fields ) { foreach ( $this->meta_box['fields'] as $field ) { // Get current post meta data. - $field_value = get_post_meta( $post->ID, $field['id'], true ); + $field_value = $this->get_field_value($post, $field); // Set standard value. if ( isset( $field['std'] ) ) { @@ -252,9 +286,19 @@ public function save_meta_box( $post_id, $post_object ) { } } + $save_as = $this->get_field_save_mode(); + $field_data = 'default' === $save_as ? array() : get_post_meta( $post_id, $this->meta_box['id'], true ); + if ( empty( $field_data ) ) { + $field_data = array(); + } + foreach ( $this->meta_box['fields'] as $field ) { - $old = get_post_meta( $post_id, $field['id'], true ); + if ( 'default' === $save_as ) { + $old = get_post_meta( $post_id, $field['id'], true ); + } else { + $old = isset( $field_data[ $field['id'] ] ) ? $field_data[ $field['id'] ] : ''; + } $new = ''; // There is data to validate. @@ -349,11 +393,19 @@ public function save_meta_box( $post_id, $post_object ) { } if ( isset( $new ) && $new !== $old ) { - update_post_meta( $post_id, $field['id'], $new ); + if ( 'default' === $save_as ) { + update_post_meta( $post_id, $field['id'], $new ); + } else { + $field_data[ $field['id'] ] = $new; + } } elseif ( '' === $new && $old ) { delete_post_meta( $post_id, $field['id'], $old ); } } + + if ( 'default' !== $save_as ) { + update_post_meta( $post_id, $this->meta_box['id'], $field_data ); + } } }