Last active
March 25, 2018 02:13
-
-
Save wkirby/6ad67c0feb58ba7171cb2fe9a091985e to your computer and use it in GitHub Desktop.
1-to-1 Relationship Fields for Carbon Fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Carbon_Fields\Field; | |
use Carbon_Fields\Exception\Incorrect_Syntax_Exception; | |
/** | |
* Taxonomy field class. | |
*/ | |
class Taxonomy_Field extends Select_Field | |
{ | |
protected $taxonomy; | |
/** | |
* Stores the taxonomy for the dropdown | |
* | |
* @var string | |
**/ | |
public function set_taxonomy($taxonomy) | |
{ | |
if ( taxonomy_exists($taxonomy) ) { | |
$this->min = $this->add_options($this->values_for_taxonomy($taxonomy)); | |
} else { | |
Incorrect_Syntax_Exception::raise('Only valid taxonomies are allowed in the <code>set_taxonomy()</code> method.'); | |
} | |
return $this; | |
} | |
private function values_for_taxonomy($taxonomy) | |
{ | |
$terms = get_terms(array('taxonomy' => $taxonomy, 'hide_empty' => false)); | |
return array_reduce($terms, function(&$result, $item) { | |
$result[$item->term_id] = $item->name; | |
return $result; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment