Skip to content
Advertisement

PHP 7.4.21 Strange Behaviour inside WordPress

I’m puzzled by the behaviour of PHP 7.4.21. Inside a WordPress page I have this piece of code:

<span class="team-member-social">
    <?php 
        if(the_field('facebook_link')) { ?>
            <a href="<?php the_field('facebook_link'); ?>"><i class="<?php the_field('facebook_icon'); ?>"></i></a>
    <?php }
        if(the_field('github_link')) { ?>
            <a href="<?php the_field('github_link'); ?>"><i class="<?php the_field('github_icon'); ?>"></i></a>
    <?php }
        if(the_field('dribble_link')) { ?>
            <a href="<?php the_field('dribble_link'); ?>"><i class="<?php the_field('dribble_icon'); ?>"></i></a>
    <?php   }
        if(the_field('tumblr_link')) { ?>
            <a href="<?php the_field('tumblr_link'); ?>"><i class="<?php the_field('tumblr_icon'); ?>"></i></a>
    <?php   } ?>
</span>

the function the_field() is a function of ACF (Advanced Custom Fields) plugin and returns a string with the content the user has set inside the custom field.

The strange behviour I’m referring to is that inside the ifs all the blocks of HTML code (<a...><i...></i></a>) is returned like a simple text containing the value of <?php the_field('XXX_link'); ?> and not in the correct format (a series of social network icons).

When I remove the ifs the pieces of code are shown correctly.

Any suggestion on how this may occur?

Advertisement

Answer

the_field() echos the data, you have to use get_field() in the if statement

From the ACF docs here

Please note this function is the same as echo get_field().

like this

<span class="team-member-social">
    <?php 
        if(get_field('facebook_link')) { ?>
            <a href="<?php the_field('facebook_link'); ?>"><i class="<?php the_field('facebook_icon'); ?>"></i></a>
    <?php }
        if(get_field('github_link')) { ?>
            <a href="<?php the_field('github_link'); ?>"><i class="<?php the_field('github_icon'); ?>"></i></a>
    <?php }
        if(get_field('dribble_link')) { ?>
            <a href="<?php the_field('dribble_link'); ?>"><i class="<?php the_field('dribble_icon'); ?>"></i></a>
    <?php   }
        if(get_field('tumblr_link')) { ?>
            <a href="<?php the_field('tumblr_link'); ?>"><i class="<?php the_field('tumblr_icon'); ?>"></i></a>
    <?php   } ?>
</span>

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement