Last active
March 23, 2018 17:44
-
-
Save chaance/28dfcf8fc04669c869a6ba4486ece54e to your computer and use it in GitHub Desktop.
Validate text input as valid URL for WordPress
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 | |
/** | |
* Validate text input as valid URL for WordPress. | |
* | |
* @param string $text Text from field. | |
*/ | |
function xx_get_field_as_link( $text ) { | |
if ( ! empty( $text ) ) { | |
// If first character of link is a /, assume a relative URL | |
if ( substr( $text, 0, 1 ) === '/' ) { | |
$text = get_home_url() . $text; | |
} | |
// If field value is an integer, assume it's the page/post ID and get URL | |
if ( ctype_digit( $text ) ) { | |
$text = get_permalink( $text ); | |
} | |
// Validate button link as a URL | |
$url = filter_var( $text, FILTER_VALIDATE_URL ) ? $text : NULL; | |
return $url; | |
} | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment