From e3c2639e80665e623e1f1f4ce93fe80babb59f09 Mon Sep 17 00:00:00 2001 From: Daniel Weipert Date: Wed, 16 Dec 2020 22:07:02 +0100 Subject: Adds Taxonomy Term Meta support --- composer.json | 2 +- src/Metabox.php | 39 +++++++++++++++++++++++++++++++++++++-- tests/MetaboxTest.php | 19 +++++++++++++++++++ 3 files changed, 57 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index c23a035..e5c651b 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "drogueronin/metaboxes", - "version": "1.0.2", + "version": "1.1.0", "type": "library", "license": "MIT", "authors": [ diff --git a/src/Metabox.php b/src/Metabox.php index b2ae2e4..b04ef00 100644 --- a/src/Metabox.php +++ b/src/Metabox.php @@ -26,6 +26,11 @@ class Metabox */ public array $posttypes = []; + /** + * The Taxonomies/s to add the Metabox to + */ + public array $taxonomies = []; + /** * The Box's fields to add * @@ -72,6 +77,24 @@ class Metabox return $this; } + /** + * Assign a Taxonomy to add the Metabox to + * + * @param string|array $taxonomies + * + * @return $this + */ + public function taxonomy($taxonomies) + { + $taxonomies = (array)$taxonomies; + + foreach ($taxonomies as $taxonomy) { + $this->taxonomies[$taxonomy] = $taxonomy; + } + + return $this; + } + /** * @param MetaboxField|array $fields * @@ -110,7 +133,7 @@ class Metabox */ public function add() { - // build the rule groups for the location + // build the post type rule groups $postTypeRuleGroups = array_map(function ($posttype) { return [[ 'param' => 'post_type', @@ -119,11 +142,23 @@ class Metabox ]]; }, $this->posttypes); + // build the taxonomy rule groups + $taxonomyRuleGroups = array_map(function ($taxonomy) { + return [[ + 'param' => 'taxonomy', + 'operator' => '==', + 'value' => $taxonomy, + ]]; + }, $this->taxonomies); + + // merge the rules groups for the location + $ruleGroups = array_merge($postTypeRuleGroups, $taxonomyRuleGroups); + // merge with extra options $fieldGroup = array_merge_recursive([ 'key' => $this->key, 'title' => $this->title, - 'location' => $postTypeRuleGroups, + 'location' => $ruleGroups, ], $this->options); // add field group diff --git a/tests/MetaboxTest.php b/tests/MetaboxTest.php index 1a1353e..e26c9f2 100644 --- a/tests/MetaboxTest.php +++ b/tests/MetaboxTest.php @@ -52,6 +52,25 @@ class MetaboxTest extends TestCase $this->assertEquals($expectedPostTypes, $this->metabox->posttypes); } + /** + * @test + */ + public function assignsTaxonomyOnce() + { + $this->metabox->taxonomy(['category', 'post_tag']); + + $expectedTaxonomies = [ + 'category' => 'category', + 'post_tag' => 'post_tag', + ]; + + $this->assertEquals($expectedTaxonomies, $this->metabox->taxonomies); + + $this->metabox->taxonomy('category'); + + $this->assertEquals($expectedTaxonomies, $this->metabox->taxonomies); + } + /** * @test */ -- cgit v1.2.3