Conditional Logic for links in ACF

708 views Asked by At

So here is what im trying to do. Im using Advanced Custom Fields for this and am outputting a title with a link, But sometimes their is NO link. When there is NO link I don't want this to be wrapped in a tag but I can't seem to figure that part out.

Here is my code for part of the page

<div class="small-12 columns">
    <h2>Show Information</h2>
    <?php if( have_rows('show_information') ): ?>
    <?php while( have_rows('show_information') ): the_row(); ?>
    <p><a href="<?php the_sub_field('show_link'); ?><?php the_sub_field('show_pdf'); ?>" target="_blank">
        <?php the_sub_field('show_title'); ?></a></p>
    <?php endwhile; ?>
    <?php endif; ?>
</div>

So how it is now i'm using the repeater field and I am displaying either a link OR PDF and a title. I ran into the issues if they do not have a link or a PDF that the title will still get wrapped in a tag and will just link back to itself in the front end. I would like if they did not put a link or a PDF attached that the tag would go away and just be text with no link.

Any help would be great.

1

There are 1 answers

0
rnevius On BEST ANSWER

You should use get_sub_field() to determine whether or not a link exists, and then use a conditional. Something like:

<div class="small-12 columns">
    <h2>Show Information</h2>
    <?php if( have_rows('show_information') ): ?>
        <?php while( have_rows('show_information') ): the_row(); ?>
            <p>
                <?php 
                    if ( get_sub_field('show_link') ) {
                        echo '<a href="' . get_sub_field('show_link') . get_sub_field('show_pdf') . '" target="_blank">';
                        echo get_sub_field('show_title') . '</a>';
                    } else { 
                        the_sub_field('show_title');
                    }
                ?>
            </p>
        <?php endwhile; ?>
    <?php endif; ?>
</div>