Validate::sanitize_tags_field( null|array $value = null, array $args = array() )

Description #

Sanitize tags field.

Sanitize keys and values. Exclude new tags if not allowed. Only include numbers of max tags allowed in field option.

Parameters #

  • $value
    null | array (Optional) Arrays of tags to sanitize. Default value: null
  • $args
    array (Optional) Tags JavaScript options. Default value: array()

Changelog #

VersionDescription
4.1.5Improved tags validation.
4.1.0Introduced.

Source #

File: lib/class-validate.php

	public static function sanitize_tags_field( $value = null, $args = array() ) {
		if ( ! empty( $value ) ) {
			$i             = 0;
			$sanitized     = array();
			$existing_tags = array();

			$args['value_field'] = empty( $args['value_field'] ) || 'name' === $args['value_field'] ? 'name' : 'id';

			foreach ( (array) $value as $tag ) {
				if ( is_numeric( $tag ) ) {
					$existing_tags[] = $tag;
				} elseif ( false !== $args['js_options']['create'] ) {
					$sanitized[] = sanitize_text_field( $tag );
				}
			}

			$taxo = ! empty( $args['terms_args']['taxonomy'] ) ? $args['terms_args']['taxonomy'] : 'question_tag';

			if ( ! empty( $existing_tags ) ) {
				$terms = get_terms(
					array(
						'taxonomy'   => $taxo,
						'include'    => $existing_tags,
						'fields'     => 'id=>name',
						'hide_empty' => false,
					)
				);

				// If allowed add new tags as well.
				if ( $terms ) {
					foreach ( $terms as $id => $tname ) {
						$sanitized[] = 'name' === $args['value_field'] ? $tname : $id;
					}
				}
			}

			return $sanitized;
		}
	}

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