-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWP_MetaForm.php
98 lines (83 loc) · 2.38 KB
/
WP_MetaForm.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
class WP_MetaForm
{
public $rawform;
public $prefix = '';
public $validator;
public $label = 'OnceForm MetaBox';
public $post_type = 'page';
protected $onceform;
public function __construct( $options, /* Callable */ $form, $validator = null )
{
$this->rawform = $form;
$this->validator = $validator;
if ( is_array( $options ) ) {
if ( !empty( $options['prefix'] ) )
$this->prefix = $options['prefix'];
if ( !empty( $options['label'] ) )
$this->label = $options['label'];
if ( !empty( $options['post_type'] ) )
$this->post_type = $options['post_type'];
// Only wire up the save_meta handler if autosave is true,
// or not set (to default to true).
if ( empty( $options['autosave'] ) )
add_action( 'save_post', array( &$this, 'save_meta') );
}
}
public function metabox()
{
if ( current_user_can( 'manage_options' ) ) {
add_meta_box( $this->prefix.'_meta_box',
$this->label,
array( &$this, 'admin_meta_box' ), $this->post_type,
'normal', 'high'
);
}
}
private function init_onceform()
{
if ( !isset( $this->onceform ) ) {
$this->onceform = new WP_OnceForm(
$this->rawform,
$this->validator
);
}
}
public function admin_meta_box( $post )
{
$this->init_onceform();
$fields = $this->onceform->get_field_names();
// load saved values from field names
$data = array();
foreach( $fields as $field ) {
if ( strstr( $field, '[]') ) {
$altn = substr( $field, 0, -2 );
$fieldname = substr( $this->prefix . $field, 0, -2 );
$data[ $altn ] = get_post_meta( $post->ID, $fieldname, true );
}
else {
$fieldname = $this->prefix . $field;
$data[ $field ] = get_post_meta( $post->ID, $fieldname, true );
}
}
// set saved forms values
$this->onceform->set_data( $data, false );
echo $this->onceform;
}
public function save_meta( $post_id )
{
if ( ! current_user_can( 'manage_options' )
|| ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
) return;
if ( !isset($_POST['post_type']) || $_POST['post_type'] != $this->post_type ) return;
// Onceform will not be available yet - so make it so
$this->init_onceform();
// save the onceform data
foreach( $this->onceform->data as $meta_key => $meta_data ) {
if ( strstr( $meta_key, '[]') ) {
$meta_key = substr( $meta_key, 0, -2 );
}
update_post_meta( $post_id, $this->prefix.$meta_key, $meta_data );
}
}
}