1 <?php
2
3 4 5 6 7 8
9
10 namespace nk2580\wordsmith\MetaBoxes;
11
12 class MetaBox {
13
14 protected $name;
15 protected $post_type;
16 protected $title;
17 protected $context = 'side';
18 protected $priority = 'default';
19 protected $fields = [
20 ['label' => "Exmple Field", 'meta-key' => "example_meta", 'control' => "nk2580\wordsmith\Inputs\Fields\TextField"],
21 ];
22
23 24 25
26 public function __construct() {
27 $this->init();
28 }
29
30 public function init() {
31 add_action('add_meta_boxes', array($this, 'add_boxes'));
32 add_action('save_post', array($this, 'save_box_content'));
33 }
34
35 36 37
38 public function add_boxes() {
39 foreach ($this->post_type as $screen) {
40 add_meta_box($this->name, $this->title, array($this, 'load_box_content'), $screen, $this->context, $this->priority);
41 }
42 }
43
44 45 46 47 48
49 public function save($post_id) {
50 foreach ($this->fields as $field) {
51 if (isset($field['options'])) {
52 $control = new $field['control']($field['meta-key'], $field['options'], $field['label'], $_POST[$field['meta-key']]);
53 } else {
54 $control = new $field['control']($field['meta-key'], $field['label'], $_POST[$field['meta-key']]);
55 }
56 if ($control->isFieldValid()) {
57 update_post_meta($post_id, $field['meta-key'], $control->sanitize());
58 }
59 else{
60 return $field['meta-key'];
61 }
62 }
63 }
64
65 66 67
68 public function verify_save($post_id) {
69
70 if (!isset($_POST[$this->name . '_box_nonce']))
71 return $post_id;
72
73 $nonce = $_POST[$this->name . '_box_nonce'];
74
75 if (!wp_verify_nonce($nonce, $this->name . '_box'))
76 return $post_id;
77
78 if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
79 return $post_id;
80
81 if ('page' == $_POST['post_type']) {
82
83 if (!current_user_can('edit_page', $post_id))
84 return $post_id;
85 } else {
86
87 if (!current_user_can('edit_post', $post_id))
88 return $post_id;
89 }
90 }
91
92 93 94 95 96
97 public function content($post) {
98 foreach ($this->fields as $field) {
99 $value = get_post_meta($post->ID, $field['meta-key'], true);
100 if (isset($field['options'])) {
101 $control = new $field['control']($field['meta-key'], $field['options'], $field['label'], $value);
102 } else {
103 $control = new $field['control']($field['meta-key'], $field['label'], $value);
104 }
105 $control->printField();
106 }
107 }
108
109 110 111
112
113 private function add_nonce() {
114
115 wp_nonce_field($this->name . '_box', $this->name . '_box_nonce');
116 }
117
118 119 120
121
122 public function load_box_content($post) {
123 $this->add_nonce();
124 $this->content($post);
125 }
126
127 128 129
130
131 public function save_box_content($post_id) {
132 $this->verify_save($post_id);
133 $this->save($post_id);
134 }
135
136 }