WordPress function – Check If URL Contains http://, Add It
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