Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds limit to post recursion when iterating through nested WordPress Posts #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions library/class-acf-to-rest-api-recursive.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

if ( ! class_exists( 'ACF_To_REST_API_Recursive' ) ) {
class ACF_To_REST_API_Recursive {

protected static $recursedPosts = [];
public static $postRecursionDepth = 1;

public static function init() {
self::hooks();
}
Expand All @@ -18,9 +22,9 @@ private static function hooks() {

protected static function get_types() {
$types = array(
'options' => 'options',
'comments' => 'comments',
'users' => 'users',
'options' => 'options',
'comments' => 'comments',
'users' => 'users'
);

$types += (array) get_post_types( array( 'show_in_rest' => true ) );
Expand All @@ -47,11 +51,15 @@ public static function get_fields( $data ) {

public static function get_fields_recursive( $item ) {
if ( is_object( $item ) ) {
if (get_class($item) === 'WP_Post') {
static::$recursedPosts[$item->ID] = static::$recursedPosts[$item->ID] ?? 0;
static::$recursedPosts[$item->ID]++;
}
$item->acf = array();

$depth = $item->depth ?? 0;
$fields = get_fields( $item );

if ( $fields ) {
if ( $fields && static::$recursedPosts[$item->ID] < static::$postRecursionDepth ) {
$item->acf = $fields;
array_walk_recursive( $item->acf, array( __CLASS__, 'get_fields_recursive' ) );
}
Expand Down