-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpost-options-api.php
546 lines (464 loc) · 16.3 KB
/
post-options-api.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
<?php
/**
* Post Options API
*
* This is not a plugin, this is a file you should bundle together with
* your theme or plugin where you'd like to use the Post Options API.
* View the Readme file for more details and examples.
*
* Version 1.0.1
* Author: Konstantin Kovshenin ([email protected])
* http://theme.fm
*
* License: GPL2
**/
/**
* Post Options Fields
*
* This is a helper class with static methods that can be used in
* callbacks when registering post options. These are used to create
* simple fields like text boxes, textareas, checkboxes and more. If
* something more customizable is needed, you can always run your own
* callback function.
*
* Methods come in pairs, the creator function (factory) and the actual callback.
* The factory function returns the callback in an array compatible with
* the post options API.
*
**/
if ( ! class_exists( 'Post_Options_Fields_1_0_1' ) ):
class Post_Options_Fields_1_0_1 {
// Used to output description if present (for less redundancy)
public static function description( $args = array() ) {
if ( isset( $args['description'] ) && ! empty( $args['description'] ) )
echo "<br /><span class='description'>{$args['description']}</span>";
}
/**
* Checkbox
*
* Give this checkbox a label and a description through
* the arguments array for the best look and feel.
**/
public static function checkbox( $args = array() ) {
$defaults = array(
'label' => '',
'description' => '',
'sanitize_callback' => '',
'sanitize_callback_args' => ''
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
return array(
'function' => array( __CLASS__, '_checkbox' ),
'sanitize_callback' => $sanitize_callback,
'sanitize_callback_args' => $sanitize_callback_args,
'args' => array(
'label' => $label,
'description' => $description
)
);
}
public static function _checkbox( $args = array() ) {
?>
<label><input type="checkbox" name="<?php echo $args['name_attr']; ?>" value="1" <?php echo checked( (bool) $args['value'] ); ?> /> <?php echo $args['label']; ?></label>
<?php
self::description( $args );
}
/**
* Text Input
*
* Factory function accepts a description and a
* sanitize_callback if you need some validation.
**/
public static function text( $args = array() ) {
$defaults = array(
'description' => '',
'sanitize_callback' => '',
'sanitize_callback_args' => '',
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
return array(
'function' => array( __CLASS__, '_text' ),
'sanitize_callback' => $sanitize_callback,
'sanitize_callback_args' => $sanitize_callback_args,
'args' => array(
'description' => $description
)
);
}
public static function _text ( $args = array() ) {
?>
<input class="large-text" type="text" name="<?php echo $args['name_attr']; ?>" value="<?php echo esc_attr( $args['value'] ); ?>" />
<?php
self::description( $args );
}
/**
* Textarea (multi-line text)
*
* Function accepts a description, rows and
* a sanitize_callback for validation.
**/
public static function textarea( $args = array() ) {
$defaults = array(
'description' => '',
'rows' => 4,
'sanitize_callback' => '',
'sanitize_callback_args' => ''
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
return array(
'function' => array( __CLASS__, '_textarea' ),
'sanitize_callback' => $sanitize_callback,
'sanitize_callback_args' => $sanitize_callback_args,
'args' => array(
'description' => $description,
'rows' => $rows
)
);
}
public static function _textarea( $args = array() ) {
?>
<textarea class="large-text" rows="<?php echo $args['rows']; ?>" name="<?php echo $args['name_attr']; ?>"><?php echo esc_textarea( $args['value'] ); ?></textarea>
<?php
self::description( $args );
}
/**
* Drop-down Select
*
* Give it a description and a select_data array where
* the array keys are the values of the options and the array
* values are the captions. The sanitize_callback argument
* is available too.
**/
public static function select( $args = array() ) {
$defaults = array(
'description' => '',
'select_data' => array(),
'sanitize_callback' => '',
'sanitize_callback_args' => ''
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
return array(
'function' => array( __CLASS__, '_select' ),
'sanitize_callback' => $sanitize_callback,
'sanitize_callback_args' => $sanitize_callback_args,
'args' => array(
'description' => $description,
'select_data' => $select_data
)
);
}
public static function _select( $args = array() ) {
?>
<select name="<?php echo $args['name_attr']; ?>">
<?php foreach ( $args['select_data'] as $value => $caption ): ?>
<option <?php echo selected( $value == $args['value'] ); ?> value="<?php echo $value; ?>"><?php echo $caption; ?></option>
<?php endforeach; ?>
</select>
<?php
self::description( $args );
}
/**
* Radio Group
*
* Works very much like the drop-down select box. The radio
* data is passed in the radio_data array. Rest is the same.
**/
public static function radio( $args = array() ) {
$defaults = array(
'description' => '',
'radio_data' => array(),
'sanitize_callback' => '',
'sanitize_callback_args' => ''
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
return array(
'function' => array( __CLASS__, '_radio' ),
'sanitize_callback' => $sanitize_callback,
'sanitize_callback_args' => $sanitize_callback_args,
'args' => array(
'description' => $description,
'radio_data' => $radio_data
)
);
}
public static function _radio( $args = array() ) {
?>
<?php foreach ( $args['radio_data'] as $value => $caption ): ?>
<label><input type="radio" name="<?php echo $args['name_attr']; ?>" value="<?php echo $value; ?>" <?php echo checked( $value == $args['value'] ); ?> > <?php echo $caption; ?></label><br />
<?php endforeach; ?>
<?php
self::description( $args );
}
// This is a Singleton class
private static $instance;
public static function singleton() {
if ( ! isset( self::$instance ) ) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
};
endif; // class_exists
/**
*
* Post Options Class
*
* All the post options logic and functions are implemented here
* and wrapper functions with simpler names could then be created
* outside the class for convenience and simplicity.
*
* This class handles registration of sections and post options to
* sections, sections to post types assignment and the actual
* metabox UI and the post meta IO operations.
*
**/
if ( ! class_exists( 'Post_Options_API_1_0_1' ) ):
class Post_Options_API_1_0_1 {
private $sections = array();
private $options = array();
private $post_types = array();
// Runs during 'init'
function __construct() {
add_action( 'admin_init', array( &$this, '_admin_init' ) );
add_action( 'submitpage_box', array( &$this, '_add_nonce_field' ) );
add_action( 'submitpost_box', array( &$this, '_add_nonce_field' ) );
}
// Runs during 'admin_init' doh!
function _admin_init() {
// Debug voodoo
//add_action('all', create_function('', 'var_dump(current_filter());'));
// Adds the metabox for each post type
foreach ( $this->post_types as $post_type => $sections )
foreach ( $sections as $section_id )
add_meta_box( 'post-options-' . $section_id, $this->sections[$section_id]['title'], array( &$this, '_meta_box_post_options' ), $post_type, $this->sections[$section_id]['context'], $this->sections[$section_id]['priority'], array( 'section_id' => $section_id ) );
// Register the save_post action (for all post types)
add_action( 'save_post', array( &$this, '_save_post' ), 10, 2 );
}
// Security check on edit pages
function _add_nonce_field() {
global $post;
if ( $post )
wp_nonce_field( 'edit_post_options_' . $post->ID , '_post_options_nonce', false );
}
// Runs during 'save_post'
function _save_post( $post_id, $post ) {
// Security check (nonce)
if ( ! isset( $_POST['_post_options_nonce'] ) || ! wp_verify_nonce( $_POST['_post_options_nonce'], 'edit_post_options_' . $post->ID ) )
return;
//check_admin_referer( '_post_options_nonce', 'aedit_post_options_' . $post->ID );
// Don't save revisions and auto-drafts
if ( wp_is_post_revision( $post_id ) || $post->post_status == 'auto-draft' )
return;
// If there are no sections in the current post type live no longer!
$post_type = $post->post_type;
if ( ! isset( $this->post_types[$post_type] ) )
return;
// Get the sections for the post type
$post_type_sections = $this->post_types[$post_type];
foreach ( $post_type_sections as $section_id ) {
// Skip inexisting sections
if ( ! $this->section_exists( $section_id ) )
continue;
$section = $this->sections[$section_id];
$section_options = $this->options[$section_id];
// Loop through the options in the section (priority voodoo).
foreach ( $section_options as $priority => $options ) {
foreach ( $options as $option_id => $option ) {
// Read the POST data, call the sanitize functions if they exist.
if ( isset( $_POST['post-options'][$option_id] ) ) {
$value = $_POST['post-options'][$option_id];
if ( isset( $option['callback']['sanitize_callback'] ) && is_callable( $option['callback']['sanitize_callback'] ) )
if ( isset( $option['callback']['sanitize_callback_args'] ) )
$value = call_user_func( $option['callback']['sanitize_callback'], $value, $option['callback']['sanitize_callback_args'] );
else
$value = call_user_func( $option['callback']['sanitize_callback'], $value );
// You can hook into here too
$value = apply_filters( 'post_options_update', $value, $option_id, $post_id );
// Update the post meta for this option.
update_post_meta( $post_id, $option_id, $value );
} else {
// You can hook here to override the delete action
$delete = (bool) apply_filters( 'post_options_delete', true, $option_id, $post_id );
if ( $delete )
delete_post_meta( $post_id, $option_id );
}
} // foreach (option)
} // foreach (priority, options)
} // foreach post type sections
}
// The meta box, oh the meta box! Runs for the meta box contents.
function _meta_box_post_options( $post, $metabox ) {
$args = $metabox['args'];
$section_id = $args['section_id'];
if ( ! $this->section_exists( $section_id ) )
return false;
$section = $this->sections[$section_id];
// Return if no fields defined
if ( empty( $this->options[$section_id] ) )
return;
// Sort the array by keys (priority)
ksort( $this->options[$section_id] );
?>
<!-- Put this in a more decent place when done with styling. -->
<style>
.post-option {
display: block;
padding: 8px 0;
border-bottom: solid 1px #eee;
line-height: 1.5;
}
.post-option label.post-option-label {
width: 20%;
display: block;
float: left;
}
.post-option .post-option-value {
display: block;
margin-left: 25%;
}
.post-option-value br+br {
display: none;
}
.post-option input,
.post-option textarea,
.post-option select {
font-size: 12px;
}
</style>
<?php
$section_options = $this->options[$section_id];
// Loop through the options.
foreach ( $section_options as $priority => $options ) {
foreach ( $options as $option_id => $option ) {
// Print the option title
echo "<div class='post-option option-{$option_id}'>";
echo "<label class='post-option-label'>{$option['title']}</label>";
echo "<div class='post-option-value'>";
// These will be sent to the callback as arguments
$args = array(
'name_attr' => "post-options[{$option_id}]",
'value' => $this->get_post_option( $post->ID, $option_id )
);
// There may be more arguments for the callback, merge them
if ( isset( $option['callback']['args'] ) && is_array( $option['callback']['args'] ) )
$args = array_merge( $args, $option['callback']['args'] );
// Fire the callback (prints the option value part).
if ( is_callable( $option['callback'] ) )
call_user_func( $option['callback'], $args );
elseif ( is_callable( $option['callback']['function'] ) )
call_user_func( $option['callback']['function'], $args );
echo "</div>";
echo "<div class='clear'></div></div>"; // Second div closes .post-option
}
}
}
// Register a post options section
public function register_post_options_section( $id, $title, $context = 'advanced', $priority = 'default' ) {
if ( ! isset( $this->sections[$id] ) ) {
$this->sections[$id] = array(
'title' => $title,
'context' => $context,
'priority' => $priority
);
return true;
}
return false;
}
/*
* Register Post Option
*
* Registers a new post option that can then be used in different
* sections for different post types. Each post option is also interpreted
* during post type save so you don't have to do the saving, we do it for you.
*/
public function register_post_option( $args ) {
$defaults = array(
'id' => null,
'title' => 'Untitled',
'callback' => '',
'section' => '',
'description' => '',
'priority' => 10
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
// Madness eh? Well $this->options is an array of sections, each array of sections is an array
// of priorities and each array of priorities is an array of options, ex:
// $this->options[section][priority][option_id] = array of options, sorry! :)
if ( ! isset( $this->options[$section][$priority][$id] ) && ( is_callable( $callback ) || ( is_array( $callback ) && is_callable( $callback['function'] ) ) ) ) {
$this->options[$section][$priority][$id] = array(
'title' => $title,
'callback' => $callback,
'description' => $description
);
return true;
}
return false;
}
/*
* Add Section to Post Type
*
* Registers a given section_id to a given post type slug (post, page, etc)
* so this function makes the section actually appear as a meta box on
* the edit screen.
*/
public function add_section_to_post_type( $section_id, $post_type ) {
if ( $this->section_exists( $section_id ) && ( ! isset( $this->post_types[$post_type] ) || ! in_array( $section_id, $this->post_types[$post_type] ) ) ) {
$this->post_types[$post_type][] = $section_id;
return true;
}
return false;
}
// Returns true if given section_id exists
private function section_exists( $section_id ) {
return array_key_exists( $section_id, $this->sections );
}
// Get post option (just a wrapper around get_post_meta)
public function get_post_option( $post_id, $option_id ) {
return get_post_meta( $post_id, $option_id, true );
}
// This is a Singleton class
private static $instance;
public static function singleton() {
if ( ! isset( self::$instance ) ) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
};
endif; // class_exists
/**
* Singleton Creators
*
* Below are the singleton creators for the Post Options API
* and the Post Options Fields if needed. This is made to ensure
* compatibility, like when two plugins are running a different
* version of the Post Options API.
*/
// Returns the Post Options API object (singleton)
if ( ! function_exists( 'get_post_options_api') ) {
function get_post_options_api( $version ) {
$class_name = 'Post_Options_API_' . str_replace( '.', '_', $version );
if ( class_exists( $class_name ) )
return call_user_func( array( $class_name, 'singleton' ) );
else
return new WP_Error( 'post-options-api-init', 'You have requested a non-existing version of the Post Options API.' );
}
}
// Returns the Post Options Fields object (singleton)
if ( ! function_exists( 'get_post_options_api_fields' ) ) {
function get_post_options_api_fields( $version ) {
$class_name = 'Post_Options_Fields_' . str_replace( '.', '_', $version );
if ( class_exists( $class_name ) )
return call_user_func( array( $class_name, 'singleton' ) );
else
return new WP_Error( 'post-options-api-fields-init', 'You have requested a non-existing version of the Post Options API Fields.' );
}
}