forked from bonny/WordPress-Simple-Fields
-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.php
1875 lines (1444 loc) · 66.4 KB
/
functions.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Functions that should be available outside the simple fields class
*/
/**
* Quicky debug a variable
*
* @param mixed $var the variable to output
* @param string $heading Optional heading/description of what you're debugging
* @return echo output
*/
if (!function_exists("sf_d")) {
function sf_d($var, $heading = "") {
$out = "";
$out .= "\n<pre class='sf_box_debug'>\n";
if ($heading && ! empty($heading)) {
$out .= "<b>" . esc_html($heading) . ":</b>\n";
}
if (is_array($var) || is_object($var)) {
$out .= htmlspecialchars( print_r($var, true), ENT_QUOTES, 'UTF-8' );
} else if( is_null($var) ) {
$out .= "Var is NULL";
} else if ( is_bool($var)) {
$out .= "Var is BOOLEAN ";
$out .= $var ? "TRUE" : "FALSE";
} else if ( is_string($var) ) {
if (strlen($var) === 0)
$out .= 'Var is empty string ("").';
else
$out .= "Var is string with length " . strlen($var) . ": " . htmlspecialchars( $var, ENT_QUOTES, 'UTF-8' );
} else {
$out .= htmlspecialchars( $var, ENT_QUOTES, 'UTF-8' );
}
$out .= "\n</pre>";
echo apply_filters( "simple_fields_debug_output", $out );
}
}
/**
* get values from a field in a field group
* deprecated, use simple_fields_value or simple_fields_values
*
* @param $post_id
* @param $field_name_or_id name as string or field group id and field id as array.
* for example array(3,2) to fetch field 2 from field group 3
* @param $single bool return a single (the first) value or all values (as array)
* @return string or array
*/
function simple_fields_get_post_value($post_id, $field_name_or_id, $single = true) {
global $sf;
$fetch_by_id = true;
if (is_array($field_name_or_id) && sizeof($field_name_or_id) == 2) {
$field_group_id = $field_name_or_id[0];
$field_id = $field_name_or_id[1];
$fetch_by_id = false;
}
$connector = simple_fields_get_all_fields_and_values_for_post($post_id);
$return_val = null;
if ($connector) {
foreach ($connector["field_groups"] as $one_field_group) {
$is_found = false;
foreach ($one_field_group["fields"] as $one_field) {
if ($fetch_by_id && $one_field["name"] == $field_name_or_id) {
$is_found = true;
} else if (!$fetch_by_id && (intval($one_field_group["id"]) === intval($field_group_id)) && (intval($one_field["id"]) === intval($field_id))) {
$is_found = true;
}
$saved_values = isset($one_field["saved_values"]) ? $one_field["saved_values"] : null;
if ($one_field["type"] == "radiobuttons" || $one_field["type"] == "dropdown") {
if ($one_field["type"] == "radiobuttons") {
$get_value_key = "type_radiobuttons_options";
} else if ($one_field["type"] == "dropdown") {
$get_value_key = "type_dropdown_options";
}
// if radiobutton or dropdown, get value from type_dropdown_options[<saved value>][value]
// for each saved value, get value from type_dropdown_options[<saved value>]
for ($saved_i = 0; $saved_i < sizeof($saved_values); $saved_i++) {
$saved_values[$saved_i] = $one_field[$get_value_key][$saved_values[$saved_i]]["value"];
}
}
// check for settings saved for the field (in gui or through register_field_group)
$parsed_options_for_this_field = array();
$field_options_key = "type_".$one_field["type"]."_options";
if (isset($one_field[$field_options_key])) {
// settings exist for this field
if (isset($one_field[$field_options_key]["enable_extended_return_values"]) && $one_field[$field_options_key]["enable_extended_return_values"]) {
$parsed_options_for_this_field["extended_return"] = 1;
}
if (isset($parsed_options_for_this_field["extended_return"]) && $parsed_options_for_this_field["extended_return"]) {
// Yep, use extended return values
$num_values = count($saved_values);
while ($num_values--) {
$saved_values[$num_values] = $sf->get_extended_return_values_for_field($one_field, $saved_values[$num_values]);
}
}
}
if ($is_found && $single) {
$return_val = $saved_values[0];
} else if ($is_found) {
$return_val = $saved_values;
}
if ($is_found) {
$return_val = apply_filters( "simple_fields_get_post_value", $return_val, $post_id, $field_name_or_id, $single);
return $return_val;
}
}
}
}
// Nothing found
$return_val = NULL;
$return_val = apply_filters( "simple_fields_get_post_value", $return_val, $post_id, $field_name_or_id, $single);
return $return_val;
}
/**
* get all values from a field group
*
* @param int $post_id
* @param name or ir $field_group_name_or_id
* @param bool use_name return array with names or id as key
* @param int $return_format 1|2
* @return array
*/
function simple_fields_get_post_group_values($post_id, $field_group_name_or_id, $use_name = true, $return_format = 1) {
$fetch_by_id = false;
if (is_numeric($field_group_name_or_id)) {
$field_group_name_or_id = (int) $field_group_name_or_id;
$fetch_by_id = true;
}
$connector = simple_fields_get_all_fields_and_values_for_post($post_id);
if (!$connector) {
$return_val = apply_filters( "simple_fields_get_post_group_values", array(), $post_id, $field_group_name_or_id, $use_name, $return_format);
return $return_val;
}
foreach ($connector["field_groups"] as $one_field_group) {
$is_found = false;
if ($fetch_by_id && $one_field_group["id"] == $field_group_name_or_id) {
$is_found = true;
} else if (!$fetch_by_id && $field_group_name_or_id == $one_field_group["name"]) {
$is_found = true;
}
if ($is_found) {
$arr_return = array();
foreach ($one_field_group["fields"] as $one_field) {
$saved_values = isset( $one_field["saved_values"] ) ? $one_field["saved_values"] : null;
if (is_null($saved_values)) {
// no saved values. just continue?
continue;
}
if ($one_field["type"] == "radiobuttons" || $one_field["type"] == "dropdown") {
if ($one_field["type"] == "radiobuttons") {
$get_value_key = "type_radiobuttons_options";
} else if ($one_field["type"] == "dropdown") {
$get_value_key = "type_dropdown_options";
}
// if radiobutton or dropdown, get value from type_dropdown_options[<saved value>][value]
// for each saved value, get value from type_dropdown_options[<saved value>]
for ($saved_i = 0; $saved_i < sizeof($saved_values); $saved_i++) {
$saved_values[$saved_i] = $one_field[$get_value_key][$saved_values[$saved_i]]["value"];
}
}
if ($use_name) {
$arr_return[$one_field["name"]] = $saved_values;
} else {
$arr_return[$one_field["id"]] = $saved_values;
}
}
$set_count = isset( $one_field["saved_values"] ) ? sizeof( $one_field["saved_values"] ) : 0;
$arr_return2 = array();
for ($i=0; $i<$set_count; $i++) {
$arr_return2[$i] = array();
foreach ($arr_return as $key => $val) {
$arr_return2[$i][$key] = $val[$i];
}
}
if ($return_format == 1) {
$arr_return = apply_filters( "simple_fields_get_post_group_values", $arr_return, $post_id, $field_group_name_or_id, $use_name, $return_format);
return $arr_return;
} elseif ($return_format == 2) {
$arr_return2 = apply_filters( "simple_fields_get_post_group_values", $arr_return2, $post_id, $field_group_name_or_id, $use_name, $return_format);
return $arr_return2;
}
}
}
}
/**
* fetch all information about the field group that a post has
* returns connector structure, field groups, fields, and values
* well.. everything! it's really funky.
*
* used from many places
*
* return @array a really fat one!
*/
function simple_fields_get_all_fields_and_values_for_post($post_id, $args = "") {
global $sf;
$cache_key = 'simple_fields_'.$sf->ns_key.'_get_all_fields_and_values_for_post_' . $post_id . "_" . md5(json_encode($args));
$selected_post_connector = wp_cache_get( $cache_key , 'simple_fields' );
if (FALSE === $selected_post_connector) {
$defaults = array(
"include_deleted" => TRUE
);
$args = wp_parse_args($args, $defaults);
$post = get_post($post_id);
$connector_to_use = $sf->get_selected_connector_for_post($post);
$existing_post_connectors = $sf->get_post_connectors();
$field_groups = $sf->get_field_groups();
$selected_post_connector = isset($existing_post_connectors[$connector_to_use]) ? $existing_post_connectors[$connector_to_use] : NULL;
if ($selected_post_connector == null) {
$return_val = FALSE;
$return_val = apply_filters( "simple_fields_get_all_fields_and_values_for_post", $return_val, $post_id, $args);
return $return_val;
}
// Remove deleted field groups
if (!$args["include_deleted"]) {
$arr_field_groups_to_keep = array();
foreach ($selected_post_connector["field_groups"] as $one_field_group_id => $one_field_group) {
if ($one_field_group["deleted"]) continue;
$arr_field_groups_to_keep[$one_field_group_id] = $one_field_group;
}
$selected_post_connector["field_groups"] = $arr_field_groups_to_keep;
}
// Do stuff
foreach ($selected_post_connector["field_groups"] as $one_field_group) { // one_field_group = name, deleted, context, priority, id
// now get all fields for that fieldgroup and join them together
$selected_post_connector["field_groups"][ $one_field_group["id"] ] = array_merge( $selected_post_connector["field_groups"][ $one_field_group["id"] ], $field_groups[ $one_field_group["id"] ] );
// Older versions don't have slug, so don't bail out if not exists
$field_group_slug = isset( $one_field_group["slug"] ) ? $one_field_group["slug"] : "";
// loop through all fields within this field group
// now find out how many times this field group has been added
// can be zero, 1 and several (if field group is repeatable)
$num_added_field_groups = 0;
$meta_key_num_added = $sf->get_meta_key_num_added( $one_field_group["id"], $field_group_slug );
while (get_post_meta($post_id, "{$meta_key_num_added}{$num_added_field_groups}", true)) {
$num_added_field_groups++;
}
// Field groups should only be allowed to be 0 if the group is repeatable
if ($num_added_field_groups == 0 && (isset($one_field_group['repeatable']) && !$one_field_group['repeatable']) ) {
$num_added_field_groups++;
}
// now fetch the stored values, one field at a time
// echo "<br>num_added_field_groups: $num_added_field_groups";
// for repeatable field groups num_added_field_groups is the number of added field groups
for ($num_in_set = 0; $num_in_set < $num_added_field_groups; $num_in_set++) {
// fetch value for each field
foreach ($selected_post_connector["field_groups"][$one_field_group["id"]]["fields"] as $one_field_id => $one_field_value) {
$one_field_group_slug = isset( $one_field_group["slug"] ) ? $one_field_group["slug"] : "";
$one_field_value_slug = isset( $one_field_value["slug"] ) ? $one_field_value["slug"] : "";
$custom_field_key = $sf->get_meta_key( $one_field_group["id"], $one_field_id, $num_in_set, $one_field_group_slug, $one_field_value_slug );
$saved_value = get_post_meta($post_id, $custom_field_key, true); // empty string if does not exist
// Modify values for some field types
if ("textarea" === $one_field_value["type"]) {
$match_count = preg_match_all('/http:\/\/[a-z0-9A-Z\.]+[a-z0-9A-Z\.\/%&=\?\-_#]+/i', $saved_value, $match);
if ($match_count) {
$links=$match[0];
for ($j=0;$j<$match_count;$j++) {
if (strpos($saved_value, 'href="'.$links[$j].'"') === false && strpos($saved_value, "href='".$links[$j]."'") === false) {
$attr['discover'] = (apply_filters('embed_oembed_discover', false)) ? true : false;
$oembed_html = wp_oembed_get($links[$j], $attr);
// If there was a result, oembed the link
if ($oembed_html) {
$saved_value = str_replace($links[$j], apply_filters('embed_oembed_html', $oembed_html, $links[$j], $attr), $saved_value);
}
}
}
}
} else if ("dropdown" === $one_field_value["type"]) {
// dropdown can be multiple since 1.1.4
if (isset($one_field_value["type_dropdown_options"]["enable_multiple"]) && $one_field_value["type_dropdown_options"]["enable_multiple"]) {
// value should always be array when using multiple
if (!is_array($saved_value)) $saved_value = array();
}
}
//
$selected_post_connector["field_groups"][$one_field_group["id"]]["fields"][$one_field_id]["saved_values"][$num_in_set] = $saved_value;
$selected_post_connector["field_groups"][$one_field_group["id"]]["fields"][$one_field_id]["meta_keys"][$num_in_set] = $custom_field_key;
}
}
}
wp_cache_set( $cache_key, $selected_post_connector, 'simple_fields' );
}
$selected_post_connector = apply_filters( "simple_fields_get_all_fields_and_values_for_post", $selected_post_connector, $post_id, $args);
return $selected_post_connector;
}
class Simple_Fields_Walker_Category_Checklist extends Walker {
var $tree_type = 'category';
var $db_fields = array ('parent' => 'parent', 'id' => 'term_id');
function start_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "$indent<ul class='children'>\n";
}
function end_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n";
}
function start_el(&$output, $category, $depth = 0, $args = array(), $current_object_id = 0) {
global $simple_fields_taxonomyterm_walker_field_name;
extract($args);
if ( empty($taxonomy) )
$taxonomy = 'category';
// @todo: use custom simple fields name for all inputs
$name = $simple_fields_taxonomyterm_walker_field_name;
$class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : '';
$output .= "\n<li $class>" . '<label class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="'.$name.'[]" ' . checked( in_array( $category->term_id, $selected_cats ), true, false ) . disabled( empty( $args['disabled'] ), false, false ) . ' /> ' . esc_html( apply_filters('the_category', $category->name )) . '</label>';
}
function end_el(&$output, $category, $depth = 0, $args = array()) {
$output .= "</li>\n";
}
}
// Returns an array for merging with WP_Query() arguments.
// TODO: A variable in simple_fields_groups that keeps track of the most number
// of times a field has been repeated on any single post so that $num_in_set can
// be determined dynamically.
function simple_fields_get_meta_query($group_id, $field_id, $value, $compare = "=", $type = "CHAR", $order = "", $num_in_set = 1) {
global $sf;
$field_group = $sf->get_field_group($group_id);
$field = $sf->get_field_in_group($field_group, $field_id);
if (!is_array($field_group) || !is_array($field)) {
return false;
}
if(!is_numeric($num_in_set) || $num_in_set < 1) {
$num_in_set = 1;
}
if ($field["type"] == "radiobuttons") {
$get_value_key = "type_radiobuttons_options";
} else if ($field["type"] == "dropdown") {
$get_value_key = "type_dropdown_options";
}
if (!empty($get_value_key) && is_array($field[$get_value_key])) {
foreach($field[$get_value_key] as $option_key => $option) {
if ($option['value'] == $value && (!isset($option['deleted']) || intval($option['deleted']) == 0)) {
$value = $option_key;
}
}
}
$query_args = array('meta_query' => array('relation' => 'OR'));
for($i=0;$i<$num_in_set;$i++) {
$query_args['meta_query'][$i]['key'] = $sf->get_meta_key( $field_group['id'], $field['id'], $i, $field_group['slug'], $field['slug'] );
$query_args['meta_query'][$i]['value'] = $value;
$query_args['meta_query'][$i]['compare'] = $compare;
$query_args['meta_query'][$i]['type'] = $type;
}
if ($order == "ASC" || $order == "DESC") {
$query_args['meta_key'] = $query_args['meta_query'][0]['key'];
$query_args['orderby'] = 'meta_value';
$query_args['order'] = $order;
}
$query_args = apply_filters( "simple_fields_get_meta_query", $query_args, $group_id, $field_id, $value, $compare, $type, $order, $num_in_set);
return $query_args;
}
/**
* Extends args for WP_Query() with simple fields meta query args
* and returns query result object
*
* Example:
* $args = array(
* "post_type" => "books",
* "sf_group" => "Book details",
* "sf_field" => "Author",
* "sf_value" => "Stephen King"
* );
*
* $my_query = simple_fields_query_posts($args);
*/
function simple_fields_query_posts($query_args = array()) {
$query_keys = array(
'sf_group',
'sf_field',
'sf_value',
'sf_compare',
'sf_type',
'sf_order',
'sf_num_in_set'
);
foreach($query_keys as $key) {
switch($key) {
case "sf_group":
case "sf_field":
case "sf_value":
if(empty($query_args[$key]))
return false;
break;
case "sf_compare":
if(empty($query_args[$key]))
$query_args[$key] = "=";
break;
case "sf_type":
if(empty($query_args[$key]))
$query_args[$key] = "CHAR";
break;
case "sf_order":
if($query_args[$key] != "ASC" && $query_args[$key] != "DESC")
$query_args[$key] = "";
break;
case "sf_num_in_set":
if(!is_numeric($query_args[$key]) || $query_args[$key] < 1)
$query_args[$key] = 1;
break;
}
}
$meta_query_args = simple_fields_get_meta_query($query_args['sf_group'], $query_args['sf_field'], $query_args['sf_value'], $query_args['sf_compare'], $query_args['sf_type'], $query_args['sf_order'], $query_args['sf_num_in_set']);
$query_args = array_merge($query_args, $meta_query_args);
$query_args = apply_filters( "simple_fields_query_posts", $query_args);
return new WP_Query($query_args);
}
/**
* Merge arrays
* Seems to combine, not write over
*/
function simple_fields_merge_arrays($array1 = array(), $array2 = array()) {
// Make sure args is arrays
$array1 = (array) $array1;
$array2 = (array) $array2;
foreach($array2 as $key => $value) {
if ( is_array($value) ) {
if ( isset( $array1[$key] ) && isset( $array2[$key] ) ) {
$array1[$key] = simple_fields_merge_arrays( $array1[$key], $array2[$key] );
} else {
// only array 2 left
$array1[$key] = $array2[$key];
}
} else {
$array1[$key] = $value;
}
}
return $array1;
}
/**
* Adds a new field group
*
* See this gist for example and more info:
* https://gist.github.com/3851387
*
* @param string $slug the slug of this field group. must be unique.
* @param array $new_field_group settings/options for the new group
* @return array the new field group as an array
*/
function simple_fields_register_field_group($slug = "", $new_field_group = array()) {
// Make sure options are not completely out of order
if ( ! is_string($slug) || ! is_array($new_field_group) ) {
_doing_it_wrong( __FUNCTION__, __("Wrong type of arguments passed", "simple-fields"), 1);
return false;
}
global $sf;
$field_groups = $sf->get_field_groups();
$highest_id = 0;
$is_new_field_group = TRUE;
$errors = new WP_Error();
// First get the id of the field group we are adding. Existing or highest new.
// Loop through all existing field groups to see if the field group we are adding already exists
// Exists = an existing field group has the same slug as the group we are adding
foreach ($field_groups as $oneGroup) {
if ($oneGroup["slug"] == $slug && !empty($slug)) {
// Field group with this slug already exists
// So we have found our field group, no need to loop further
$field_group_id = $oneGroup["id"];
$is_new_field_group = FALSE;
break;
} else if ($oneGroup["id"] > $highest_id) {
// We have not found a field id yet
// and the id of the current group is higher than the current highest id
$highest_id = $oneGroup["id"];
}
}
// If a new field group then new field group should get the id of the highest field group id + 1
// If this is the very first field group created then it gets num 1
if ($is_new_field_group) {
$highest_id++;
$field_group_id = $highest_id;
}
// Set default values for slug and name
if (empty($slug)) {
// Make sure that the field group gets a slug
$slug = "field_group_" . $field_group_id;
} else if ( ! isset($new_field_group["name"]) || empty($new_field_group["name"]) ) {
// Slug is given, but no field group name = use slug as name
$new_field_group["name"] = $slug;
}
// Make sure slug is valid
$slug = sanitize_key($slug);
// Set up default values
if ($is_new_field_group) {
$field_group_defaults = array(
"id" => $field_group_id,
"key" => $slug,
"slug" => $slug,
"name" => "Unnamed field group $field_group_id",
"description" => "",
"repeatable" => false,
"fields" => array(),
"fields_by_slug" => array(),
"deleted" => false,
"gui_view" => "list", // list | table
"added_with_code" => true
);
} else {
// This is an existing field group so get values from existing group
$field_group_defaults = $field_groups[$field_group_id];
// make sure all values are set
// added_with_code since 1.2.4
if ( ! isset( $field_group_defaults["added_with_code"] ) ) $field_group_defaults["added_with_code"] = true;
// Add the field id of each field to fields array, since the keys get lost when merging below
$field_group_defaults["fields_by_slug"] = array();
if ( is_array( $field_group_defaults["fields"] ) && sizeof( $field_group_defaults["fields"] > 0 ) ) {
// Check for deleted fields
// Check for fields that exists among the saved values, but that are not in the new array of fields = that field should be considered deleted
// a slug in $field_group_defaults["fields"] does not exist in $new_field_group["fields"] = mark that field as deleted
foreach ( $field_group_defaults["fields"] as $one_field_key => $one_field ) {
if ( ! isset( $one_field["slug"] ) || empty( $one_field["slug"] ) ) continue;
if ( ! isset( $new_field_group["fields"] ) || ! is_array( $new_field_group["fields"] ) ) continue;
$old_field_was_found_among_new_fields = false;
foreach ( $new_field_group["fields"] as $one_new_field ) {
if ( isset( $one_new_field["slug"] ) && ! empty( $one_new_field["slug"] ) && $one_new_field["slug"] === $one_field["slug"] ) {
$old_field_was_found_among_new_fields = true;
break;
}
}
if ( ! $old_field_was_found_among_new_fields) {
// echo "<br>not found, considered deleted:"; sf_d($one_field);
// unset( $field_group_defaults["fields"][ $one_field_key ] );
$field_group_defaults["fields"][ $one_field_key ]["deleted"] = true;
}
} // foreach
// Create an array with all fields by slug, for faster/easier access
foreach ( $field_group_defaults["fields"] as $field_id => & $field_array ) {
$field_array["id"] = $field_id;
$field_slug = isset( $field_array["slug"] ) ? $field_array["slug"] : "field_$field_id";
$field_group_defaults["fields_by_slug"][$field_slug] = $field_array;
} // foreach
}
} // if new or not
// Find the highest existing id. New fields will get this id plus one
// Note that the highest ID is not the last, since the order of the keys is in custom order, not ascending
if ( isset($field_groups[$field_group_id]["fields"]) && is_array($field_groups[$field_group_id]["fields"]) && sizeof($field_groups[$field_group_id]["fields"]) > 0) {
$field_id = max( array_keys( $field_groups[$field_group_id]["fields"] ) ) + 1;
} else {
$field_id = 0;
}
// Add fields by slug for new fields
$new_field_group["fields_by_slug"] = array();
if ( isset($new_field_group["fields"]) ) {
foreach ( $new_field_group["fields"] as $field_array ) {
$new_field_group["fields_by_slug"][$field_array["slug"]] = $field_array;
}
}
// Merge the new values of this field group with the old values
// Let the new values overwrite the hold ones
// This merge is the reason why we use fields_by_slug
$field_groups[$field_group_id] = simple_fields_merge_arrays($field_group_defaults, $new_field_group);
// Now the existing fields that has new values, has new values
// Brand new fields have no id set, so thats how we can detect them
// If the field group has an array of fields
if ( isset($new_field_group["fields"]) && is_array($new_field_group["fields"]) && ! empty($new_field_group["fields"]) ) {
// Loop through all fields that are passed to function,
// make sure new fields has all necessary keys and values
foreach ( $new_field_group["fields_by_slug"] as $one_new_field ) {
// Set up default values for this field
// New field get highest taken id + 1
$field_defaults = array(
"id" => "",
"name" => "",
"slug" => "",
"description" => "",
"type" => "",
"type_post_options" => array(
"enabled_post_types" => array(),
"additional_arguments" => ""
),
"type_taxonomyterm_options" => array(
"additional_arguments" => ""
),
"id" => NULL,
"deleted" => 0,
// add general field options
// each field has its own array here, with field key as key
// old format with type_<field name>_options was/is kinda crappy
"options" => array(),
);
// If a field with this index/id exists then merge that values of that field with our default values
// so if you add one field in php, then one in the gui, and then extend the php with one more field =
// field from gui is overwritten since it get's the id that the php version want
// use only slug instead and we should be fine
// Find id of possibly existing field using the slug
// If existing field is found then merge old values with new
// If fields exist for the old/saved field group, then merge new fields with old ones
// If existing/old field does not exist then use defaults directly
if ( isset( $field_groups[$field_group_id]["fields"] ) && is_array( $field_groups[$field_group_id]["fields"] ) ) {
// Check if our current field has an old version
// Loop through all fields to find any field with our slug
if ( isset( $field_groups[$field_group_id]["fields_by_slug"][$one_new_field["slug"]] ) ) {
$existing_field_array_from_slug = & $field_groups[$field_group_id]["fields_by_slug"][$one_new_field["slug"]];
// Update old/existings fields by mergering with new fields
$field_defaults = simple_fields_merge_arrays($field_defaults, $existing_field_array_from_slug );
// Do stuff with field default values
// Key = name, slug, type etc.
// Value = string, array, etc.
foreach ($field_defaults as $oneDefaultFieldKey => $oneDefaultFieldValue) {
if ($oneDefaultFieldKey === "id") {
// If this is a field with no id set, then it's a new field that should get a id
if ( is_null($oneDefaultFieldValue) || $oneDefaultFieldValue === "" ) {
#echo "<br>new field - added id $field_id";
$existing_field_array_from_slug["id"] = $field_id;
$field_id++;
}
}
// If a value in the new/updated field is an array
// and is among the default values keys, and it's is not empty
// then if the key is an old school option field with name type_<field type>_options
// then set defaults for that array
if ( isset($one_new_field[$oneDefaultFieldKey]) && is_array($one_new_field[$oneDefaultFieldKey]) && !empty($one_new_field[$oneDefaultFieldKey]) ) {
// If this is an array with options for a field type
// For example "type_post_options" or "type_taxonomyterm_options"
$options_type = preg_replace("/type_([a-z]+)_options/i", '$1', $oneDefaultFieldKey);
if ( ! empty($options_type) ) {
// Do things the old way. No slugs used here.
foreach ( array_keys($one_new_field[$oneDefaultFieldKey]) as $optionKey ) {
// Only continue if key is numeric
// This code will generate the "dropdown_num_1"-stuff
// and the number is based on the index (the array key)
if ( is_numeric($optionKey) ) {
if ("radiobuttons" === $options_type) $options_type = "radiobutton";
$newOptionKey = $options_type . "_num_" . $optionKey;
$existing_field_array_from_slug[$oneDefaultFieldKey][$newOptionKey] = $one_new_field[$oneDefaultFieldKey][$optionKey];
unset($existing_field_array_from_slug[$oneDefaultFieldKey][$optionKey]);
$optionKey = $newOptionKey;
}
// mark value as non-deleted if deleted is not in the array of dropdown/radiobutton values
if ( isset( $existing_field_array_from_slug[$oneDefaultFieldKey][$optionKey]) && is_array($existing_field_array_from_slug[$oneDefaultFieldKey][$optionKey]) && ! empty($existing_field_array_from_slug[$oneDefaultFieldKey][$optionKey]["value"]) ) {
if ( ! isset( $existing_field_array_from_slug[$oneDefaultFieldKey][$optionKey]["deleted"]) ) {
$existing_field_array_from_slug[$oneDefaultFieldKey][$optionKey]["deleted"] = 0;
}
}
} // foreach
} // if not empty options type
} // if isset
// If default value does not exist in new field then add it
if ( ! isset( $existing_field_array_from_slug[$oneDefaultFieldKey] ) ) {
$existing_field_array_from_slug[$oneDefaultFieldKey] = $oneDefaultFieldValue;
}
} // foreach field default
// Setup new options array that exists since 1.2
// existing_field_array_from_slug = the merged array, with old + new options
// new values from arg = $one_new_field
// move new options to sub-array by field type
$arr_merged_options = isset($one_new_field["options"]) ? wp_parse_args( $one_new_field["options"] ) : array();
// Make sure options key for this field type exists
if ( ! isset( $existing_field_array_from_slug["options"][ $existing_field_array_from_slug["type"] ] ) ) {
$existing_field_array_from_slug["options"][ $existing_field_array_from_slug["type"] ] = array();
}
// what about for example "type_post_options" that may already exist?
// if they exist, move to merge with options, then merge with options, before new values are merged
// do that first since those values are the oldest (pre-upgrade pre-save values)
/*
sf_d( isset( $existing_field_array_from_slug[ "type_". $existing_field_array_from_slug["type"] . "_options" ] ) );
sf_d( $existing_field_array_from_slug[ "type_". $existing_field_array_from_slug["type"] . "_options" ] );
This array will alsways exist after we've added a field
Array
(
[0] => Array
(
[num] => 1
[value] => Stor
)
)
*/
#echo "<br>before:<br>";
#sf_d($arr_merged_options);
if ( isset( $existing_field_array_from_slug[ "type_". $existing_field_array_from_slug["type"] . "_options" ] ) ) {
# denna ökar antalet dropdown values vid varje körning
#sf_d( $existing_field_array_from_slug[ "type_". $existing_field_array_from_slug["type"] . "_options" ] );
$arr_old_vals_to_merge = array();
$arr_old_vals_to_merge_values = array();
foreach ( $existing_field_array_from_slug[ "type_". $existing_field_array_from_slug["type"] . "_options" ] as $one_key => $one_val ) {
// $new_values_key = ( "radiobuttons" === $one_new_field["type"] ) ? "radiobutton_num_" : "dropdown_num_";
if ( strpos( $one_key, "dropdown_num_" ) !== FALSE || strpos( $one_key, "radiobutton_num_" ) !== FALSE ) {
$num = str_replace( array("dropdown_num_", "checkbox_num_"), "", $one_key );
$one_val["num"] = $num;
$arr_old_vals_to_merge_values[] = $one_val;
} else {
$arr_old_vals_to_merge[ $one_key ] = $one_val;
}
$arr_old_vals_to_merge["values"] = $arr_old_vals_to_merge_values;
} // foreach
#$arr_merged_options = array_merge( $existing_field_array_from_slug[ "type_". $existing_field_array_from_slug["type"] . "_options" ], $arr_merged_options );
#sf_d($arr_old_vals_to_merge);
$arr_merged_options = array_merge( $arr_old_vals_to_merge, $arr_merged_options );
}
#sf_d($arr_merged_options);
#echo "<br>after:<br>";
#sf_d($arr_merged_options);
// Merge in new values, overwriting existing, but also letting existing keys that have no new value be
# denna ökar antalet dropdown values vid varje körning
$arr_merged_options = array_merge( $existing_field_array_from_slug["options"][ $existing_field_array_from_slug["type"] ], $arr_merged_options );
$existing_field_array_from_slug["options"][ $existing_field_array_from_slug["type"] ] = $arr_merged_options;
/*
problem with field group values from multiple sources:
Example below: "products" and "monkeys" won't get removed, due. to merge.. well.. merging!
Instead array sent in to function as arg should be allowed to overwrite existing array
But only overwrite keys that already exists, leaving other keys
If this is the already stored format (from for example GUI, or from previous register_field_group)
[post] => Array
(
[enabled_post_types] => Array
(
[0] => post
[1] => page
[2] => products
[3] => monkeys
)
[additional_arguments] => cat=10
[enable_extended_return_values] => 1
)
And this is the new as sent in as arg to register_field_group:
[post] => Array
(
[enabled_post_types] => Array
(
[0] => post
[1] => page
)
[additional_arguments] => cat=10
[enable_extended_return_values] => 1
)
*/
// Remove the keys we added from the options array (just keep them in the sub-array)
$new_options_keys = isset( $one_new_field["options"] ) ? array_keys( (array) $one_new_field["options"] ) : array();
// if someone did enter values like this:
// options[field_type] => array(options..)
// then don't break that by removing
if ( isset( $one_new_field["type"] ) && ( $key_to_remove_pos = array_search( $one_new_field["type"], $new_options_keys ) ) !== FALSE ) {
unset( $new_options_keys[ $key_to_remove_pos ] );
unset( $existing_field_array_from_slug["options"][ $one_new_field["type"] ][ $one_new_field["type"] ] );
}
// Remove the keys we added from the options array (but keep them in the sub-array)
foreach ( $new_options_keys as $one_key_to_remove ) {
unset( $existing_field_array_from_slug["options"][ $one_key_to_remove ] );
}
// Fix dropdown and radiobuttons values for the array in with the "options" key
// If field type is dropdown or radiobuttons then convert new format to old format,
// because old format is used internally in many places
if ( isset( $one_new_field["type"] ) && ( $one_new_field["type"] === "dropdown" || $one_new_field["type"] === "radiobuttons" ) ) {
if ( isset( $one_new_field["options"]["values"] ) && is_array( $one_new_field["options"]["values"] ) ) {
$new_values = array();
$did_set_checked_by_default = FALSE;
foreach ( $one_new_field["options"]["values"] as $one_dropdown_or_radio_value ) {
// Each value must have num and value
if ( ! isset( $one_dropdown_or_radio_value["value"] ) || ! isset( $one_dropdown_or_radio_value["value"] ) ) continue;
$new_values_key = ( "radiobuttons" === $one_new_field["type"] ) ? "radiobutton_num_" : "dropdown_num_";
$new_values_key .= isset( $one_dropdown_or_radio_value["num"] ) ? (int) $one_dropdown_or_radio_value["num"] : 0;
$new_values[ $new_values_key ] = array(
"value" => $one_dropdown_or_radio_value["value"],
"deleted" => isset( $one_dropdown_or_radio_value["deleted"] ) ? (bool) $one_dropdown_or_radio_value["deleted"] : FALSE
);
// "checked_by_default_num" => "radiobutton_num_2"
if ( isset( $one_dropdown_or_radio_value["checked"] ) && TRUE === $one_dropdown_or_radio_value["checked"] ) {
$new_values["checked_by_default_num"] = $new_values_key;
$did_set_checked_by_default = TRUE;
}
} // foreach
if ( FALSE === $did_set_checked_by_default ) $new_values["checked_by_default_num"] = NULL;
// Unset all existing radiobuttons or dropdowns
// This will remove dropdowns/radiobuttons that are not in the new field setup,
// and it will make sure that the order is the new order
foreach ( $arr_merged_options as $one_key => $one_val ) {
// radiobutton_num_10 dropdown_num_2
if ( strpos( $one_key, "dropdown_num_" ) !== FALSE || strpos( $one_key, "radiobutton_num_" ) !== FALSE ) {
unset( $arr_merged_options[ $one_key ] );
}
}
$arr_merged_options = array_merge($arr_merged_options, $new_values);
#echo 111; sf_d($arr_merged_options);
} // if
} // if
/*
is like:
[options] => Array
(
[dropdown] => Array
(
[enable_extended_return_values] => 1
[enable_multiple] => 1
[values] => Array
(
[0] => Array
(
[num] => 0
[value] => Yes New
[deleted] => 1
[possibly_other_stuff_in_future] => yes
)
[1] => Array
(