WordPress custom field echoing whole URL

My code is as below:

<?php   
if( get_field( "facebook" ) !== '' ): ?>
<a href="<?php echo the_field('facebook'); ?>">Facebook</a>
<?php endif;?>

Instead of echoing the field’s value which is (wwww.facebook.com), it’s echoing it relative to the wordpress website.

Read More

Also, is my code efficient? Or is there a simpler way to do it?

Edit: What finally worked for me:

<?php
$website =  (get_field('website'));
if(!empty($website)){
$final_url = (!preg_match("~^(?:f|ht)tps?://~i", $website))? 'http://'.$website: $website;
echo "<a href="$final_url">$final_url</a>" . "<br />";
}
?>  

Related posts

Leave a Reply

1 comment

  1. you should add http:// on the beggining to make external URLS

    <a href="http://<?php echo the_field('facebook'); ?>">Facebook</a>
    

    or add http:// on your advanced custom field in the admin

    EDIT:

    here is your final code:

    $url = the_field('facebook');
    
    if($url!=""){
        $final_url = (!preg_match("~^(?:f|ht)tps?://~i", $url))? 'http://'.$url: $url;
        echo '<a href="'.$final_url.'">Facebook</a><br/>';
    }
    

    NOTE:

    • your data wwww.facebook.com has excess w
    • i appended the code given by @feeela so it would check if http:// is present, thanks to @feeela