Check for the presence of the http: // URL at the beginning and insert if not

I am currently editing a wordpress theme with custom field outputs. I successfully made all the changes and everything works as it should. My problem is that if the URL is sent to a custom field, the echo is exactly what was there, so if someone goes to www.somesite.com, the echo just adds it to the end of the domain : www.mysite.com www.somesite.com. I want to check if the supplied channel has the http:// prefix at the beginning, if it then performs both actions, but if it does not output http:// in front of the URL.

I hope I explained my problem as best as I can.

 $custom = get_post_meta($post->ID, 'custom_field', true); <?php if ( get_post_meta($post->ID, 'custom_field', true) ) : ?> <a href="<?php echo $custom ?>"> <img src="<?php echo bloginfo('template_url');?>/lib/images/social/image.png"/></a> <?php endif; ?> 
+7
source share
3 answers

parse_url() can help ...

 $parsed = parse_url($urlStr); if (empty($parsed['scheme'])) { $urlStr = 'http://' . ltrim($urlStr, '/'); } 
+53
source

You can check if http:// at the beginning of the line using strpos () .

 $var = 'www.somesite.com'; if(strpos($var, 'http://') !== 0) { return 'http://' . $var; } else { return $var; } 

Thus, if it does not have http:// at the very beginning of var, it will return http:// in front of it. Otherwise, it will simply return $var .

+8
source
 echo (strncasecmp('http://', $url, 7) && strncasecmp('https://', $url, 8) ? 'http://' : '') . $url; 

Remember that strncmp() returns 0 when the first letters of n are equal, which evaluates to false . This can be a bit confusing.

+1
source

All Articles