1: <?php
2:
3: 4: 5: 6:
7: class Papi_Property_Term extends Papi_Property {
8:
9: 10: 11: 12: 13:
14: public $convert_type = 'object';
15:
16: 17: 18: 19: 20:
21: public function get_default_settings() {
22: return [
23: 'taxonomy' => '',
24: 'select2' => true,
25: 'query' => []
26: ];
27: }
28:
29: 30: 31: 32: 33: 34: 35:
36: protected function get_terms( $settings ) {
37:
38: $args = array_merge( $settings->query, [
39: 'fields' => 'id=>name'
40: ] );
41:
42: return get_terms( $settings->taxonomy, $args );
43: }
44:
45: 46: 47:
48: public function html() {
49: $settings = $this->get_settings();
50: $value = $this->get_value();
51:
52: if ( is_object( $value ) ) {
53: $value = $value->term_id;
54: } else {
55: $value = 0;
56: }
57:
58: $classes = 'papi-fullwidth';
59:
60: if ( $settings->select2 ) {
61: $classes = ' papi-component-select2';
62: }
63: ?>
64: <div class="papi-property-term">
65: <?php if ( empty( $settings->taxonomy ) ): ?>
66: <p><?php _e( 'No taxonomy defined for term property', 'papi' ); ?></p>
67: <?php else:
68: $terms = $this->get_terms( $settings );
69: ?>
70: <select
71: id="<?php echo $this->html_id(); ?>"
72: name="<?php echo $this->html_name(); ?>"
73: class="<?php echo $classes; ?>"
74: data-allow-clear="true"
75: data-placeholder="<?php echo isset( $settings->placeholder ) ? $settings->placeholder : ''; ?>"
76: data-width="100%">
77:
78: <?php if ( isset( $settings->placeholder ) ): ?>
79: <option value=""></option>
80: <?php endif; ?>
81:
82: <?php foreach ( $terms as $term_id => $term_name ) : ?>
83: <?php
84: papi_render_html_tag( 'option', [
85: 'value' => $term_id,
86: 'selected' => $value === $term_id ? 'selected' : null,
87: $term_name
88: ] );
89: ?>
90: <?php endforeach; ?>
91:
92: </select>
93: <?php endif; ?>
94: </div>
95: <?php
96: }
97:
98: 99: 100: 101: 102: 103: 104: 105: 106:
107: public function import_value( $value, $slug, $post_id ) {
108: if ( is_object( $value ) && isset( $value->term_id ) ) {
109: return $value->term_id;
110: }
111:
112: if ( is_numeric( $value ) ) {
113: return (int) $value;
114: }
115:
116: return $this->default_value;
117: }
118:
119: 120: 121: 122: 123: 124: 125: 126: 127:
128: public function format_value( $value, $slug, $post_id ) {
129: if ( is_numeric( $value ) && intval( $value ) !== 0 ) {
130: $settings = $this->get_settings();
131: return get_term( $value, $settings->taxonomy );
132: }
133:
134: return $this->default_value;
135: }
136: }
137: