Skip to content

Commit

Permalink
Add save_mode for metaboxes
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
gdarko committed Mar 27, 2022
1 parent e128926 commit cb2ccd6
Showing 1 changed file with 55 additions and 3 deletions.
58 changes: 55 additions & 3 deletions src/Metabox.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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'] ) ) {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 );
}
}

}

0 comments on commit cb2ccd6

Please sign in to comment.