array( 'label' => __( 'Text', 'glovario' ) ), 'multiline' => array( 'label' => __( 'Multiline text', 'glovario' ) ), 'url' => array( 'label' => __( 'URL', 'glovario' ) ), 'email' => array( 'label' => __( 'Email', 'glovario' ) ), 'number' => array( 'label' => __( 'Number', 'glovario' ) ), 'image' => array( 'label' => __( 'Image', 'glovario' ) ), ); /** * Filter registered variable types. * * Each type requires a translatable label. Custom sanitization, validation, * and rendering can use the dedicated filters below. */ return apply_filters( 'glovario_supported_variable_types', $types ); } public function exists( $type ) { // Imports and filters can pass anything; only a string can name a type. return is_string( $type ) && isset( $this->all()[ $type ] ); } public function sanitize( $value, $type ) { switch ( $type ) { case 'multiline': $value = sanitize_textarea_field( $value ); break; case 'url': $value = esc_url_raw( $value ); break; case 'email': $value = sanitize_email( $value ); break; case 'number': $value = sanitize_text_field( $value ); break; case 'image': // The attachment ID of an image in the Media Library. $value = absint( $value ) ? (string) absint( $value ) : ''; break; default: $value = sanitize_text_field( $value ); } return apply_filters( 'glovario_sanitized_variable_value', $value, $type ); } public function validate( $value, $type ) { if ( ! $this->exists( $type ) ) { return new \WP_Error( 'invalid_type', __( 'Select a supported variable type.', 'glovario' ) ); } if ( 'url' === $type && '' !== $value && ! wp_http_validate_url( $value ) ) { return new \WP_Error( 'invalid_url', __( 'Enter a valid HTTP or HTTPS URL.', 'glovario' ) ); } if ( 'email' === $type && '' !== $value && ! is_email( $value ) ) { return new \WP_Error( 'invalid_email', __( 'Enter a valid email address.', 'glovario' ) ); } if ( 'number' === $type && '' !== $value && ! is_numeric( $value ) ) { return new \WP_Error( 'invalid_number', __( 'Enter a valid number.', 'glovario' ) ); } if ( 'image' === $type && '' !== (string) $value && ! self::is_image( $value ) ) { return new \WP_Error( 'invalid_image', __( 'Choose an image from the Media Library.', 'glovario' ) ); } return apply_filters( 'glovario_validate_variable_value', true, $value, $type ); } /** * Whether a value is the ID of an image attachment. * * @param mixed $value Candidate attachment ID. * @return bool */ public static function is_image( $value ) { $id = is_scalar( $value ) && ctype_digit( trim( (string) $value ) ) ? absint( $value ) : 0; return $id && 'attachment' === get_post_type( $id ) && wp_attachment_is_image( $id ); } }