WordPress function – Check If URL Contains http://, Add It


About The Author
Avatar Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







WordPress function – Check If URL Contains http://, Add It

Here’s your quick snippet for the day.  Yesterday, I was using Advanced Custom Fields text field to enter data and populate it on the frontend.  The issue was that users would be populating this field themselves and I wouldn’t know whether the URL contained the initial http:// protocol.  To solve this, a quick addition to my functions.php file in WordPress did the trick.  Here’s the function:

function addhttp($url) {
 if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
 $url = "http://" . $url;
 }
 return $url;
}

Once the above function was added I would utilize it on my theme using something like the following.  Note I am using Advanced Custom Fields here and pulling in a link to a users Facebook:

<a href="<?php echo addhttp(get_field('facebook_link', 'option')); ?>" target="_blank">Link To Facebook</a>

Now whether my client enters their Facebook URL with or without the http:// or https:// protocol, my link will function correctly.


Share Your Thoughts

Leave a Reply

Your email address will not be published. Required fields are marked *


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!