How to add a protocol to URLs from WordPress post content

Sometimes you have URLs without http:// OR https:// into WordPress post content.

So you can use the following function for that. You can use this function for the_content filter for WP. And also you can use this anywhere in PHP code other than WP.

<?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;
}

How to Import – Export WordPress Database using WP-CLI | WP-CLI | WordPress

I’ve made a video for this tutorial. Because that’s the easiest way to show how we can use WP-CLI to import/export database.

And if you like the video then subscribe my channel and share this with others who want to learn WordPress.

How to create a Custom Taxonomy | WordPress | Beginners Tutorial

I’ve made a video for this tutorial. Because that’s the easiest way to show how WordPress widgets work. And this is especially for beginners. So please watch the video carefully and I am sure you will definitely clear about WordPress Taxonomies.

And if you like the video then subscribe my channel and share this with others who want to learn WordPress.

Make WordPress Development soooo easy using WP SCAFFOLD COMMAND | WordPress | WP-CLI | WordPress Development

Check out my new video premiering on 29th Jul 2020 at 10:00 AM IST to Make WordPress Development soooo easy using WP SCAFFOLD COMMAND.

Enable reminder for the premiere so that you won’t miss the video.

SUBSCRIBE THE CHANNEL NOW: https://lnkd.in/gs3i6Me

 

 

How To Create Custom Widget In WordPress VERY EASY | WordPress | WordPress Development

Check out my new video premiering on 28th Jul 2020 at 9:45 AM IST for how to create a custom widget.

Enable reminder for the premiere so that you won’t miss the video.

SUBSCRIBE THE CHANNEL NOW: https://lnkd.in/gs3i6Me