acf_field_taxonomy::get_ajax_query()publicACF 5.0.9

get_ajax_query

This function will return an array of data formatted for use in a select2 AJAX response

Метод класса: acf_field_taxonomy{}

Хуки из метода

Возвращает

(Массив).

Использование

$acf_field_taxonomy = new acf_field_taxonomy();
$acf_field_taxonomy->get_ajax_query( $options );
$options **
-
По умолчанию: array()

Список изменений

С версии 5.0.9 Введена.

Код acf_field_taxonomy::get_ajax_query() ACF 6.0.4

function get_ajax_query( $options = array() ) {

	// defaults
	$options = acf_parse_args(
		$options,
		array(
			'post_id'   => 0,
			's'         => '',
			'field_key' => '',
			'paged'     => 0,
		)
	);

	// load field
	$field = acf_get_field( $options['field_key'] );
	if ( ! $field ) {
		return false;
	}

	// bail early if taxonomy does not exist
	if ( ! taxonomy_exists( $field['taxonomy'] ) ) {
		return false;
	}

	// vars
	$results         = array();
	$is_hierarchical = is_taxonomy_hierarchical( $field['taxonomy'] );
	$is_pagination   = ( $options['paged'] > 0 );
	$is_search       = false;
	$limit           = 20;
	$offset          = 20 * ( $options['paged'] - 1 );

	// args
	$args = array(
		'taxonomy'   => $field['taxonomy'],
		'hide_empty' => false,
	);

	// pagination
	// - don't bother for hierarchial terms, we will need to load all terms anyway
	if ( $is_pagination && ! $is_hierarchical ) {

		$args['number'] = $limit;
		$args['offset'] = $offset;

	}

	// search
	if ( $options['s'] !== '' ) {

		// strip slashes (search may be integer)
		$s = wp_unslash( strval( $options['s'] ) );

		// update vars
		$args['search'] = $s;
		$is_search      = true;

	}

	// filters
	$args = apply_filters( 'acf/fields/taxonomy/query', $args, $field, $options['post_id'] );

	// get terms
	$terms = acf_get_terms( $args );

	// sort into hierachial order!
	if ( $is_hierarchical ) {

		// update vars
		$limit  = acf_maybe_get( $args, 'number', $limit );
		$offset = acf_maybe_get( $args, 'offset', $offset );

		// get parent
		$parent = acf_maybe_get( $args, 'parent', 0 );
		$parent = acf_maybe_get( $args, 'child_of', $parent );

		// this will fail if a search has taken place because parents wont exist
		if ( ! $is_search ) {

			// order terms
			$ordered_terms = _get_term_children( $parent, $terms, $field['taxonomy'] );

			// check for empty array (possible if parent did not exist within original data)
			if ( ! empty( $ordered_terms ) ) {

				$terms = $ordered_terms;

			}
		}

		// fake pagination
		if ( $is_pagination ) {

			$terms = array_slice( $terms, $offset, $limit );

		}
	}

	// append to r
	foreach ( $terms as $term ) {

		// add to json
		$results[] = array(
			'id'   => $term->term_id,
			'text' => $this->get_term_title( $term, $field, $options['post_id'] ),
		);

	}

	// vars
	$response = array(
		'results' => $results,
		'limit'   => $limit,
	);

	// return
	return $response;

}