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.

* Fix the URLs from the content.
* This function will add protocol to URLs which has no protocol added.
* For example,
* –>
* –>
* –>
* @param string $content Content.
* @return string Content with fixed URLs.
function fix_content_urls( $content = '' ) {
// Bail, if anything goes wrong.
if ( empty( $content ) ) {
// 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;

Related Articles

Add custom filter for searching post or users in WordPress backend

For this, two parts are important. Part 1: Adding select dropdown Below is the action by which we can add a new search filter for…

First WordCamp

I am going to tell you about my first WordCamp which was held in Pune on 15th Jan 2017. And yes I was very happy…

PHPCode Sniffer + Sublime on windows

Things you need for: cmder composer Sublime Text 2/3 We are going to install using composer, because it will automatically install related packages. So no…

Install wp-cli on windows

WP-CLI is a set of command-line tools for managing WordPress installations. You can update plugins, configure multisite installs and much more, without using a web browser.

So I am going to tell you short, simple and easy way that how to use wp-cli on windows system.

90 mins

Hi there,   So 90 mins, I am not writing about a movie. This is a real experience for 90 minutes at ATM queue. This…


Leave a Reply