@@ -8,39 +8,25 @@ class URL_Input_Field extends Text_Input_Field {
88 /**
99 * @param mixed $value
1010 */
11- public function sanitize_field ( $ value ): string {
12- $ value = sanitize_text_field ( (string ) $ value );
13- if ( ! $ value ) {
14- return '' ;
15- }
16-
17- // Validate the URL format
18- if ( false !== wp_http_validate_url ( $ value ) ) {
19- return $ value ;
20- }
21-
22- // Clean and fix the URL and allow curly braces for parameter replacement
23- $ value = $ this ->fix_url ( $ value );
24-
25- // Sanitize while preserving placeholders
26- $ value = str_replace ( ['{ ' , '} ' ], ['___OPEN___ ' , '___CLOSE___ ' ], $ value );
27- $ value = esc_url_raw ( $ value );
28- return str_replace ( ['___OPEN___ ' , '___CLOSE___ ' ], ['{ ' , '} ' ], $ value );
29- }
30-
31- private function fix_url ( string $ value ): string {
32- // Remove HTML tags, trim, encode spaces, add protocol
33- $ value = preg_replace ( '/<(?!\{)[^>]+>/ ' , '' , $ value );
34- $ value = trim ( str_replace ( ' ' , '%20 ' , $ value ) );
35-
36- if ( $ value && ! preg_match ( '/^https?:\/\//i ' , $ value ) ) {
37- $ protocol = is_ssl () ? 'https:// ' : 'http:// ' ;
38- $ value = $ protocol . ltrim ( $ value , '/ ' );
39- }
40-
41- return $ value ;
42- }
43-
11+ public function sanitize_field ( $ value ): string {
12+ $ value = sanitize_text_field ( (string ) $ value );
13+ if ( '' === $ value ) {
14+ return '' ;
15+ }
16+
17+ // Validate the URL format.
18+ if ( false !== wp_http_validate_url ( $ value ) ) {
19+ return $ value ;
20+ }
21+
22+ // Clean and fix the URL and allow curly braces for parameter replacement.
23+ $ value = $ this ->fix_url ( $ value );
24+
25+ // Sanitize while preserving placeholders.
26+ $ value = str_replace ( [ '{ ' , '} ' ], [ '___OPEN___ ' , '___CLOSE___ ' ], $ value );
27+ $ value = esc_url_raw ( $ value );
28+ return str_replace ( [ '___OPEN___ ' , '___CLOSE___ ' ], [ '{ ' , '} ' ], $ value );
29+ }
4430
4531 /**
4632 * URL input field constructor.
@@ -50,4 +36,26 @@ private function fix_url( string $value ): string {
5036 public function get_input_type (): string {
5137 return 'url ' ;
5238 }
39+
40+ /**
41+ * Fixes the URL by removing HTML tags, trimming whitespace, encoding spaces, and adding a protocol if missing.
42+ *
43+ * @param string $value
44+ */
45+ private function fix_url ( string $ value ): string {
46+ // Remove HTML tags, trim, encode spaces, add protocol.
47+ $ value = preg_replace ( '/<(?!\{)[^>]+>/ ' , '' , $ value );
48+ $ value = trim ( str_replace ( ' ' , '%20 ' , (string ) $ value ) );
49+
50+ if ( '' === $ value ) {
51+ return '' ;
52+ }
53+
54+ $ has_prootocol = preg_match ( '/^https?:\/\//i ' , $ value ) === 1 ;
55+ if ( $ has_prootocol ) {
56+ return $ value ;
57+ }
58+ $ protocol = is_ssl () ? 'https:// ' : 'http:// ' ;
59+ return $ protocol . ltrim ( $ value , '/ ' );
60+ }
5361}
0 commit comments