acf_field_gallery::ajax_get_sort_orderpublicACF 5.0.0

AJAX handler for getting the attachment sort order.

Method of the class: acf_field_gallery{}

No Hooks.

Returns

void. Nothing (null).

Usage

$acf_field_gallery = new acf_field_gallery();
$acf_field_gallery->ajax_get_sort_order();

Changelog

Since 5.0.0 Introduced.

acf_field_gallery::ajax_get_sort_order() code ACF 6.8.8

public function ajax_get_sort_order() {
	$order = 'DESC';
	$args  = acf_parse_args(
		$_POST, // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified below.
		array(
			'ids'       => 0,
			'sort'      => 'date',
			'field_key' => '',
			'nonce'     => '',
		)
	);

	if ( ! acf_verify_ajax( $args['nonce'], $args['field_key'], true, 'gallery' ) ) {
		wp_send_json_error();
	}

	// Reverse order.
	if ( $args['sort'] === 'reverse' ) {
		$ids = array_reverse( $args['ids'] );
		wp_send_json_success( $ids );
	}

	// Ascending order.
	if ( $args['sort'] === 'title' ) {
		$order = 'ASC';
	}

	// Find attachments (DISTINCT POSTS).
	$ids = get_posts(
		array(
			'post_type'   => 'attachment',
			'numberposts' => -1,
			'post_status' => 'any',
			'post__in'    => $args['ids'],
			'order'       => $order,
			'orderby'     => $args['sort'],
			'fields'      => 'ids',
		)
	);

	if ( ! empty( $ids ) ) {
		wp_send_json_success( $ids );
	}

	wp_send_json_error();
}