Skip to content

Fix ACF get_fields method #2

@asadowski10

Description

@asadowski10
<?php
        /**
	 * Get the fields acf like name => key
	 *
	 * @return array
	 */
	protected function get_fields() {
		if ( ! is_null( $this->fields ) ) {
			return $this->fields;
		}

		// Get all groups
		$groups = acf_get_field_groups();
		if ( empty( $groups ) ) {
			return array();
		}

		// Filter has location
		$groups = array_filter( $groups, array( $this, 'filter_has_location' ) );
		if ( empty( $groups ) ) {
			return array();
		}

		$fields = array();
		foreach ( $groups as $group ) {
			// Filter location array
			$g_location = array_filter( $group['location'], array( $this, 'filter_location' ) );

			foreach ( $g_location as $loc ) {
				// Filter CPT
				$_location = array_filter( $loc, array( $this, 'filter_post_type' ) );

				if ( empty( $_location ) ) {
					continue;
				}

				$_fields = (array) acf_get_fields( $group );
				foreach ( $_fields as $_field ) {
					$fields[] = $_field;
				}

			}
		}

		$acf_fields = array();
		foreach ( $fields as $field ) {
			$acf_fields[ $field['name'] ] = $field['key'];
		}

		// Set the object available fields
		$this->fields = $acf_fields;

		return $acf_fields;
	}

	/**
	 * @param $group
	 *
	 * @return bool
	 * @author Alexandre Sadowski
	 */
	protected function filter_location( $group ) {
		return is_array( $group );
	}

	/**
	 * @param $group
	 *
	 * @return bool
	 * @author Alexandre Sadowski
	 */
	protected function filter_has_location( $group ) {
		return is_array( $group['location'] );
	}

	/**
	 * @param $cpt
	 *
	 * @return bool
	 * @author Alexandre Sadowski
	 */
	protected function filter_post_type( $cpt ) {
		return ( 'post_type' === $cpt['param'] && '==' === $cpt['operator'] && $this->post_type === $cpt['value'] );
	}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions