Skip to content

Instantly share code, notes, and snippets.

@jrudenstam
Created November 19, 2013 20:11
Show Gist options
  • Save jrudenstam/7551729 to your computer and use it in GitHub Desktop.
Save jrudenstam/7551729 to your computer and use it in GitHub Desktop.
Will get value from an Advanded Custom Field recursively. Meaning traversing up until value is found.
<?php
/*
* Get ACF fields recursivly
* (if post does not have value look upward until found)
*/
function get_field_recursive( $field, $level_id = null ) {
// If no ID is passed set to post ID
$level_id = $level_id == null ? get_queried_object_id() : $level_id;
$return_value = get_field($field, $level_id);
$ancestors = get_post_ancestors($level_id);
if ( $return_value ) {
// Return field value when found
return $return_value;
} else if ( $ancestors ) {
// Get closes ancector: http://codex.wordpress.org/Function_Reference/get_post_ancestors
$level_id = $ancestors[0];
return get_field_recursive($field, $level_id);
} else {
// Return false if value is not found nor have ancestors
return false;
}
}
?>
@eoutvik
Copy link

eoutvik commented Feb 12, 2014

Just what I needed :) Thnx for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment