1
votes

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

2 Answers

1
votes

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.

1
votes

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()