Created
May 28, 2015 15:15
-
-
Save pburke/1dd447fb306555e01b2b to your computer and use it in GitHub Desktop.
ACF Page Ancestor rule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Modified from: https://github.com/zzgael/wordpress-acf-custom-location-rule-descendant-of-page | |
*/ | |
add_filter('acf/location/rule_types', 'custom_acf_location_rules_types'); | |
function custom_acf_location_rules_types( $choices ) { | |
$choices['Page']['page_ancestor'] = 'Page Ancestor'; | |
return $choices; | |
} | |
add_filter('acf/location/rule_values/page_ancestor', 'custom_acf_location_rules_values_page_ancestor'); | |
function custom_acf_location_rules_values_page_ancestor( $choices ) { | |
// code modified from: plugins/advanced-custom-fields/core/controllers/field_group.php | |
$post_type = 'page'; | |
$posts = get_posts(array( | |
'posts_per_page' => -1, | |
'post_type' => $post_type, | |
'orderby' => 'menu_order title', | |
'order' => 'ASC', | |
'post_status' => 'any', | |
'suppress_filters' => false, | |
'update_post_meta_cache' => false, | |
)); | |
if( $posts ) { | |
// sort into hierachial order! | |
if( is_post_type_hierarchical( $post_type ) ) { | |
$posts = get_page_children( 0, $posts ); | |
} | |
foreach( $posts as $page ) { | |
$title = ''; | |
$ancestors = get_ancestors($page->ID, 'page'); | |
if($ancestors) { | |
foreach($ancestors as $a) | |
{ | |
$title .= '- '; | |
} | |
} | |
$title .= apply_filters( 'the_title', $page->post_title, $page->ID ); | |
// status | |
if($page->post_status != "publish") { | |
$title .= " ($page->post_status)"; | |
} | |
$choices[ $page->ID ] = $title; | |
} | |
} | |
return $choices; | |
} | |
add_filter('acf/location/rule_match/page_ancestor', 'custom_acf_location_rules_match_page_ancestor', 10, 3); | |
function custom_acf_location_rules_match_page_ancestor( $match, $rule, $options ) { | |
global $post; | |
$match = false; | |
$selectedPageID = (int) $rule['value']; | |
$ancestors = get_post_ancestors( $post->ID ); | |
$match = in_array($selectedPageID, $ancestors); | |
if($rule['operator'] == "==") { | |
return $match; | |
} | |
else if ($rule['operator'] == "!=") { | |
return !$match; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment