AnsPress_Ajax::search_tags()

Description #

Ajax callback for ap_search_tags. This was called by tags field for fetching tags suggestions.

Changelog #

VersionDescription
4.1.5Introduced.

Source #

File: includes/ajax-hooks.php

	public static function search_tags() {
		$q          = ap_sanitize_unslash( 'q', 'r' );
		$form       = ap_sanitize_unslash( 'form', 'r' );
		$field_name = ap_sanitize_unslash( 'field', 'r' );

		if ( ! anspress_verify_nonce( 'tags_' . $form . $field_name ) ) {
			wp_send_json( '{}' );
		}

		// Die if not valid form.
		if ( ! anspress()->form_exists( $form ) ) {
			ap_ajax_json( 'something_wrong' );
		}

		$field = anspress()->get_form( $form )->find( $field_name );

		// Check if field exists and type is tags.
		if ( ! is_a( $field, 'AnsPress\Form\Field\Tags' ) ) {
			ap_ajax_json( 'something_wrong' );
		}

		$taxo = $field->get( 'terms_args.taxonomy' );
		$taxo = ! empty( $taxo ) ? $taxo : 'tag';

		$terms = get_terms(
			array(
				'taxonomy'   => $taxo,
				'search'     => $q,
				'count'      => true,
				'number'     => 20,
				'hide_empty' => false,
				'orderby'    => 'count',
			)
		);

		$format = array();

		if ( $terms ) {
			foreach ( $terms as $t ) {
				$format[] = array(
					'term_id'     => $t->term_id,
					'name'        => $t->name,
					'description' => $t->description,
					// translators: %d is question count.
					'count'       => sprintf( _n( '%d Question', '%d Questions', $t->count, 'anspress-question-answer' ), $t->count ),
				);
			}
		}

		wp_send_json( $format );
	}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment