1

Trying to check if $link has http:// in front of it or not. If someone puts in www.google.com for the link field it acts as a link within the WordPress site, ie: www.website.com/www.google.com.

$link = get_field('advertisement_link');

$ad_code = '<a href="'.$link.'" target="_blank">Test</a>';

Sample code above I am working with. This is a general PHP question as well. How do I do this the right way? Tried below, replaces the_content() with the $link.

$link = get_field('advertisement_link');

if(strpos($link, 'http://') !== 0) {
    return 'http://' . $link;
} else {
    return $link;
}

$ad_code = '<a href="'.$link.'" target="_blank">Test</a>';

Edit: I need to keep $ad_code because I'm using it inside return prefix_insert_after_paragraph( $ad_code, 3, $content ); to insert this ad into a post every 3 paragraphs.

2

You must not return the value, but alter the varialbe $link

if(strpos($link, 'http://') !== 0) {
    $link = 'http://' . $link;
} //no else needed

Be aware that if your link begins with https:// it will also prepend the http:// and result in http://https://example.com.

The better way to do this would be from here, adjusted to your needs:

In functions.php:

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

Code for you:

$link = addhttp( get_field('advertisement_link') );
$ad_code = '<a href="'.$link.'" target="_blank">Test</a>';
  • Worked! Can't thank you enough. Elegant way to parse the data through in a concise, easy to understand way. I replaced $url with $link which I assume is the correct way? Worked either way, though. – Alexander Graham Feb 24 '16 at 15:17
  • @AlexanderGraham you don't need to do that, as this variable is just used in this function. You can call it anything you want - even $wordpressstackexchange.com, as long as you use the same variable everywhere in this function. – fischi Feb 24 '16 at 15:22
  • understood, makes sense. – Alexander Graham Feb 24 '16 at 15:23
1

I guess this is a possible duplicate of – or at least similar to "Checking if string contains HTTP://" over at stackoverflow – but still: First instead of checking for "0" you should check for "false". And then you should also check for "https://". I would probably do something like this:

if (substr($link, 0, 7) == 'http://') {
    // do nothing
} elseif (substr($link, 0, 8) == 'https://') {
    // do nothing
} else {
    $link = 'http://'.$link;
}

( I'm aware there are more elegant ways to write this )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.