Last active
December 12, 2020 09:23
-
-
Save BhargavBhandari90/67489aad26967f6afe2d6e52f278cc99 to your computer and use it in GitHub Desktop.
Add a protocol to URLs from WordPress post content
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 | |
/** | |
* Fix the URLs from the content. | |
* | |
* This function will add protocol to URLs which has no protocol added. | |
* | |
* For example, | |
* | |
* google.com --> http://google.com | |
* https://google.com --> https://google.com | |
* http://google.com --> http://google.com | |
* | |
* @param string $content Content. | |
* @return string Content with fixed URLs. | |
*/ | |
function fix_content_urls( $content = '' ) { | |
// Bail, if anything goes wrong. | |
if ( empty( $content ) ) { | |
return; | |
} | |
// Get all the links. | |
preg_match_all( '/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $content, $result ); | |
$search = $replace = array(); | |
// Create search & replace array. | |
if ( isset( $result['href'] ) && ! empty( $result['href'] ) ) { | |
foreach ( $result['href'] as $url ) { | |
$parsed_url = parse_url( $url ); | |
// If no protocol found, then add it for replacement. | |
if ( ! empty( $parsed_url ) && ! isset( $parsed_url['scheme'] ) ) { | |
$search[] = $url; // Original URL. | |
$replace[] = esc_url( $url ); // Fixed URL. | |
} | |
} | |
// Fix the URLs. | |
$content = str_replace( $search, $replace, $content ); | |
// Freeup the variables. | |
unset( $search ); | |
unset( $replace ); | |
} | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment