Created
September 12, 2022 05:12
-
-
Save dlxsnippets/49868400bc37b270cb782b1a9a67d270 to your computer and use it in GitHub Desktop.
Sanitize Block Attributes When They Are Passed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Sanitize an attribute based on type. | |
* | |
* @param array $attributes Array of attributes. | |
* @param string $attribute The attribute to sanitize. | |
* @param string $type The type of sanitization you need (values can be integer, text, float, boolean, url). | |
* | |
* @return mixed Sanitized attribute. wp_error on failure. | |
*/ | |
public static function sanitize_attribute( $attributes, $attribute, $type = 'text' ) { | |
if ( isset( $attributes[ $attribute ] ) ) { | |
switch ( $type ) { | |
case 'raw': | |
return $attributes[ $attribute ]; | |
case 'post_text': | |
case 'post': | |
return wp_kses_post( $attributes[ $attribute ] ); | |
case 'string': | |
case 'text': | |
return sanitize_text_field( $attributes[ $attribute ] ); | |
case 'bool': | |
case 'boolean': | |
return filter_var( $attributes[ $attribute ], FILTER_VALIDATE_BOOLEAN ); | |
case 'int': | |
case 'integer': | |
return absint( $attributes[ $attribute ] ); | |
case 'float': | |
if ( is_float( $attributes[ $attribute ] ) ) { | |
return $attributes[ $attribute ]; | |
} | |
return 0; | |
case 'url': | |
return esc_url( $attributes[ $attribute ] ); | |
case 'default': | |
return new \WP_Error( 'alerts_dlx_unknown_type', __( 'Unknown type.', 'alerts-dlx' ) ); | |
} | |
} | |
return new \WP_Error( 'alerts_dlx_attribute_not_found', __( 'Attribute not found.', 'alerts-dlx' ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment