forked from Hube2/acf-filters-and-functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpage-nth-level-location-rule.php
83 lines (77 loc) · 2.16 KB
/
page-nth-level-location-rule.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
<?php
/*
ACF custom location rule : Page Level
level "1" = top level parent page
this should work on any hierarchical post type?
*/
add_filter('acf/location/rule_types', 'acf_location_rules_page_level');
function acf_location_rules_page_level($choices) {
$choices['Page']['page_level'] = 'Page Level';
return $choices;
}
add_filter('acf/location/rule_operators', 'acf_location_rules_page_level_operators');
function acf_location_rules_page_level_operators($choices) {
// remove operators that you do not need
$new_choices = array(
'<' => 'is less than',
'<=' => 'is less than or equal to',
'>=' => 'is greater than or equal to',
'>' => 'is greater than'
);
foreach ($new_choices as $key => $value) {
$choices[$key] = $value;
}
return $choices;
}
add_filter('acf/location/rule_values/page_level', 'acf_location_rules_values_page_level');
function acf_location_rules_values_page_level($choices) {
// adjust the for loop to the number of levels you need
for($i=1; $i<=10; $i++) {
$choices[$i] = $i;
}
return $choices;
}
add_filter('acf/location/rule_match/page_level', 'acf_location_rules_match_page_level', 10, 3);
function acf_location_rules_match_page_level($match, $rule, $options) {
if (!isset($options['post_id'])) {
return $match;
}
$post_type = get_post_type($options['post_id']);
$page_parent = 0;
if (!$options['page_parent']) {
$post = get_post($options['post_id']);
$page_parent = $post->post_parent;
} else {
$page_parent = $options['page_parent'];
}
if (!$page_parent) {
$page_level = 1;
} else {
$ancestors = get_ancestors($page_parent, $post_type);
$page_level = count($ancestors) + 2;
}
$operator = $rule['operator'];
$value = $rule['value'];
switch ($operator) {
case '==':
$match = ($page_level == $value);
break;
case '!=':
$match = ($page_level != $value);
break;
case '<':
$match = ($page_level < $value);
break;
case '<=':
$match = ($page_level <= $value);
break;
case '>=':
$match = ($page_level >= $value);
break;
case '>':
$match = ($page_level > $value);
break;
} // end switch
return $match;
}
?>