1

I need help breaking apart the php code that's inside the tag. Basically I only want the button to appear if there is a link. If there is no link, I don't want the empty button to appear. Any ideas how to do this?

<div class="button"><a href="<?php the_sub_field( 'funding_link' ); ?>">Donate</a></div>
2
  • Add a condition? What issue are you facing? Commented Dec 26, 2018 at 21:17
  • Basically, the full issue I'm facing is that I'm trying to create a custom post type template for the first time, and I want certain post-type content to appear if there is any content in it. Commented Dec 26, 2018 at 21:23

3 Answers 3

2

the_sub_field() function may produce output (the link), or not.

The first thing to do is capture that output using an output buffer in order to check it's contents:

<?php
    ob_start();
    the_sub_field( 'funding_link' );
    $link = ob_get_clean();

Next just check the content of $link: if not an empty string then output the button's HTML code

    if( $link != "" )
    {
        echo "<div class=\"button\"><a href=\"$link\">Donate</a></div>";
    }

Finally close the PHP code block

?>

If you're using advanced custom fields then

the_sub_field(...)

is equivalent to

echo get_sub_field(...)

In this case the solution is simplier as you can just get the link into a variable without using a buffer:

<?php
    $link = get_sub_field( 'funding_link' );
    if( $link != "" )
    {
        echo "<div class=\"button\"><a href=\"$link\">Donate</a></div>";
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

0

Ok guys, I appreciate everyone's help. I figured this out with the following addition

<?php if( get_sub_field('funding_link') ): ?>
<div class="button"><a href="<?php the_sub_field( 'funding_link' ); ?>">Donate</a></div>
<?php endif; ?>

Comments

-1

As far as i can see you have html on your php file, one way to do it is like this

<?php
    $mycondition = false;
    // your condition should be something like
    // $mycondition = the_sub_field( 'funding_link' );
    // if the string is empty it's also considered a false value
?>
<?php if($mycondition):?>
    <a href="somelink.html">Donate</a>
<?php else:?>
    <!--here goes nothing-->
<?php endif;?>

Another way to do it with a shothand if

<?=($condition)?"let's show the link":"let's show nothing"?>

Try it online!

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.