Advanced Custom Fields/PHP issue

I apologize if this is answered elsewhere, but I’m having an issue with this ACF code here: http://goo.gl/9onrFN I want the client to be able to add a portfolio site link (if applicable) to the artist page and the link would say “View Artist’s Website” and the link would take the user to the artist’s site in a new window. How would I go about not making this text not visible, unless there was a url entered into the custom field on the post? Here’s the code:

<p><?php the_field('contact_phone_number'); ?><br />
                    or <a href="mailto:<?php the_field('contact_email'); ?>"><?php the_field('contact_email'); ?></a><br />
                    View <a href="<?php the_field('artist_website'); ?>" target="_blank">Artist's Website</a></p>

Thanks in advance!

Related posts

Leave a Reply

1 comment

  1. You can check if a ACF field is set with:

    if(get_field('artist_website')) {
        the_field('artist_website');
    }
    

    Using the_field will simple echo the contents of your field, whereas get_field will return the value which is a lot more helpful. For example you could write the above code as:

    Note: get_field simple returns the value of the field, if you want to check if a valid url has been entered you will have to use a regular expression.

    Below is your code with an if statement performing an empty field check:

    <p>
    <?php the_field('contact_phone_number'); ?><br />
    or <a href="mailto:<?php the_field('contact_email'); ?>"><?php the_field('contact_email'); ?></a>
    <?php if(get_field('artist_website')) { ?>
        <br />View <a href="<?php the_field('artist_website'); ?>" target="_blank">Artist's Website</a>
    

    You may find your code easier to read by pre-setting your variables and including HTML in the echo:

    <p>
    <?php
    $contact_phone_number = get_field('contact_phone_number');
    $contact_email = get_field('contact_email');
    $artist_website = get_field('artist_website');
    
    echo "{$contact_phone_number}<br />";
    echo "or <a href='mailto:{$contact_email}'>{$contact_email}</a><br/ >;
    if($artist_website) {
         echo "View <a href='{$artist_website}' target='_blank'>Artist's website</a>";
    }
    ?>
    </p>