1

I was hoping somebody may be able to help me. I'm having trouble with if statements with the Advanced Custom Fields plugin for Wordpress. I've got three options the user can choose from, all three can be chosen, but they can also choose just one if they wish.

The issue I'm having is the code I've written displays all of the HTML tags, even the empty ones. This is causing styling issues. I want to be able to just show HTML that has been populated. I've tried the solutions on the ACF forums but to no avail.

Link: http://www.advancedcustomfields.com/resources/getting-started/code-examples/

Here's the quick (newbie!) code I've got at the minute:

<a href="<?php the_sub_field('link'); ?>"><?php the_sub_field('link'); ?></a>
<a href="<?php the_sub_field('doc'); ?>"><?php the_sub_field('doc'); ?></a>
<p><?php the_sub_field('cap'); ?></p>

I looked on the ACF forum and tried this, but it broke the theme:

<?php if(the_sub_field('link')) {
    echo '<a href="' . the_sub_field('link') . '">' . the_sub_field('link') . '</a>';
} ?>

<?php if(the_sub_field('doc')) {
    echo '<a href="' . the_sub_field('doc') . '">' . the_sub_field('doc') . '</a>';
} ?>

 <?php if(the_sub_field('cap')) {
     echo '<p>' . the_sub_field('cap') . '</p>';
 } ?>

I'm looking for some help to make this work. I don't think I'm too far away from the right answer, however I'm a bit of a rookie with anything beyond standard front-end stuff, any thoughts would be very much appreciated.

Thanks!

2 Answers 2

1

Try to use get_sub_field();

<?php if(get_sub_field('link')) {
    echo '<a href="' . the_sub_field('link') . '">' . the_sub_field('link') . '</a>';
} ?>

<?php if(get_sub_field('doc')) {
    echo '<a href="' . the_sub_field('doc') . '">' . the_sub_field('doc') . '</a>';
} ?>

 <?php if(get_sub_field('cap')) {
     echo '<p>' . the_sub_field('cap') . '</p>';
 } ?>

When looping through one of these fields, this function returns a sub field from the current row.

Sign up to request clarification or add additional context in comments.

Comments

1

Like Dk-Macadamia said, try to use get_sub_field() in loops instead of the_sub_field() the difference is get_sub_field() return the value as a string, and the_sub_field() print the data,

Also get_sub_field() only work under a repeater/ fluid field type otherwise wont work, if its not a sub field of repeater/fluid fields just try get_field()

Comments

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.