Reputation: 1020
I have a custom field (called 'website') where a user enters the website to their URL. My php code is as follows
<div class="profileInfo">
<h4 class="website">Website:</h4>
<?php if ( get_post_meta($post->ID, 'website', true)) { ?>
<p><a href="http://<?php echo get_post_meta($post->ID, 'website', true) ?>"><?php echo get_post_meta($post->ID, 'website', true) ?></a></p>
<?php } else { ?>
<p class="na">no email provided</p>
<?php } ?>
</div>
In the above example I prefix the URL with http://
So my problem is, when a user enters a url like http://www.example.com to the custom field it does not link to the site correctly. The URL looks like this on the frontend http//www.example.com
Strangely the colon : is stripped away or taken out so the URL does not work!I assume this is something to do with having two http://
Now, I have tried removing the http:// from the PHP code liek this
<p><a href="<?php echo get_post_meta($post->ID, 'website', true) ?>"><?php echo get_post_meta($post->ID, 'website', true) ?></a></p>
So let's say the user now enters www.example.com to the custom field and publishes the entry. The Url now goes to
http://mysite.com/www.example.com
It tries to build the URL into my current site page. No idea why it does not treat it as a URL.
Looking for some help how to correctly write this code in PHP.
Thanks
Upvotes: 2
Views: 1973
Reputation: 801
<?php
if ( get_post_meta($post->ID, 'website', true))
{
$link = get_post_meta($post->ID, 'website', true);
$link = str_replace(array('http://','https://'), array('',''), $link);
?><p><a href="http://<?=$link?>"><?=$link?></a></p><?php
}
else
{
?><p class="na">no email provided</p><?
}
?>
This will replace all http:// in the url.
Upvotes: 6