Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Created September 3, 2015 02:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jtsternberg/323fb2ebc983cfc65cce to your computer and use it in GitHub Desktop.
From 7f6cdcb57832569001a8dc9c806d0c21c5667d6b Mon Sep 17 00:00:00 2001
From: Justin Sternberg <justin@dsgnwrks.pro>
Date: Wed, 2 Sep 2015 22:14:32 -0400
Subject: [PATCH 1/1] Handle adding fields properly if they are passed as an
array to the cmb config
---
includes/CMB2.php | 31 ++++++++++++++++++++++++++++---
1 file changed, 28 insertions(+), 3 deletions(-)
diff --git includes/CMB2.php includes/CMB2.php
index 983e5fb..b7b3ec5 100644
--- includes/CMB2.php
+++ includes/CMB2.php
@@ -121,10 +121,16 @@ class CMB2 {
}
$this->meta_box = wp_parse_args( $meta_box, $this->mb_defaults );
+ $this->meta_box['fields'] = array();
+
$this->object_id( $object_id );
$this->mb_object_type();
$this->cmb_id = $meta_box['id'];
+ if ( ! empty( $meta_box['fields'] ) && is_array( $meta_box['fields'] ) ) {
+ $this->add_fields( $meta_box['fields'] );
+ }
+
CMB2_Boxes::add( $this );
/**
@@ -139,9 +145,9 @@ class CMB2 {
/**
* Loops through and displays fields
- * @since 1.0.0
- * @param int $object_id Object ID
- * @param string $object_type Type of object being saved. (e.g., post, user, or comment)
+ * @since 1.0.0
+ * @param int $object_id Object ID
+ * @param string $object_type Type of object being saved. (e.g., post, user, or comment)
*/
public function show_form( $object_id = 0, $object_type = '' ) {
$object_type = $this->object_type( $object_type );
@@ -824,6 +830,25 @@ class CMB2 {
}
/**
+ * When fields are added in the old-school way, intitate them as they should be
+ * @since 2.1.0
+ * @param array $fields Array of fields to add
+ * @param mixed $parent_field_id Parent field id or null
+ */
+ protected function add_fields( $fields, $parent_field_id = null ) {
+ foreach ( $fields as $field ) {
+
+ $field_id = $parent_field_id
+ ? $this->add_group_field( $parent_field_id, $field )
+ : $this->add_field( $field );
+
+ if ( array_key_exists( 'fields', $field ) ) {
+ $this->add_fields( $field['fields'], $field_id );
+ }
+ }
+ }
+
+ /**
* Add a field to the metabox
* @since 2.0.0
* @param array $field Metabox field config array
--
2.2.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment