1

I apologize if this is answered elsewhere, but I'm having an issue with ACF code. 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!

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response. Could you elaborate more on your second example? What exactly I need to add and where?
Figured it out:<?php if(get_field('artist_website')) { ?> View<a href="<?php the_field('artist_website'); ?>" target="_blank"> Artist's Website</a><?php } ?>
@user2263554 Glad its working for you. Can you tick my answer as the answer please - the code you used is the same as I gave.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.