From d6fabbd1e2396e9fb68e7cc8a4ea23417cc7d763 Mon Sep 17 00:00:00 2001 From: Daniel Weipert Date: Wed, 16 Dec 2020 19:12:18 +0100 Subject: Initial commit --- src/Metabox.php | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 src/Metabox.php (limited to 'src/Metabox.php') diff --git a/src/Metabox.php b/src/Metabox.php new file mode 100644 index 0000000..0f4c5d7 --- /dev/null +++ b/src/Metabox.php @@ -0,0 +1,137 @@ +key = 'group_' . str_replace(['_', '-', '/', ' '], '_', strtolower($title)); + $this->title = $title; + + $this->options($options); + } + + /** + * Assign a PostType to add the Metabox to + * + * @param string|array $posttypes + * + * @return $this + */ + public function posttype($posttypes) + { + $posttypes = (array)$posttypes; + + foreach ($posttypes as $posttype) { + $this->posttypes[$posttype] = $posttype; + } + + return $this; + } + + /** + * @param MetaboxField|array $fields + * + * @return $this + */ + public function field($fields) + { + if ($fields instanceof MetaboxField) { + $fields = [$fields]; + } + + foreach ($fields as $field) { + // set the field's parent + $field->parent($this->key); + + $this->fields[$field->key] = &$field; + } + + return $this; + } + + /** + * @param array $options + * + * @return $this + */ + public function options(array $options) + { + $this->options = $options; + + return $this; + } + + /** + * Add the acf local field group + */ + public function add() + { + // build the rule groups for the location + $postTypeRuleGroups = array_map(function ($posttype) { + return [[ + 'param' => 'post_type', + 'operator' => '==', + 'value' => $posttype, + ]]; + }, $this->posttypes); + + // merge with extra options + $fieldGroup = array_merge_recursive([ + 'key' => $this->key, + 'title' => $this->title, + 'location' => $postTypeRuleGroups, + ], $this->options); + + // add field group + acf_add_local_field_group($fieldGroup); + + // add fields + foreach ($this->fields as $field) { + $field->add(); + } + } +} -- cgit v1.2.3