简体   繁体   中英

php if statement custom fields wordpress

I am using custom post/field types in wordpress and some of the fields are social media links.

What I am trying to do is hide the social media icon if the field is left blank in the back end of wordpress, the code below only shows/hides ALL of the icons, i need them to act independently.

<?php $socialmedia = get_post_meta( $post->ID, 'socialmedia', true );
                                                if ($socialmedia) {
                                                    foreach( $socialmedia as $socialmedia ) { ?>
                                                        <a href="http://<?php echo $socialmedia['facebook'] ?>"><img src="<?php bloginfo('template_url'); ?>/img/facebook.png" alt="facebook" width="55" height="56" /></a>
                                                        <a href="http://<?php echo $socialmedia['twitter'] ?>"><img src="<?php bloginfo('template_url'); ?>/img/twitter.png" alt="twitter" width="55" height="56" /></a>
                                                        <a href="http://<?php echo $socialmedia['soundcloud'] ?>"><img src="<?php bloginfo('template_url'); ?>/img/soundcloud.png" alt="soundcloud" width="55" height="56" /></a>
                                        <?php } // end foreach
                                        } // end if ?>

You can add if condition inside of foreach loop -

if ($socialmedia) {
    foreach( $socialmedia as $media ) {
        if($media['facebook'] != NULL) { ?> // same for other icons
            <a href="http://<?php echo $media['facebook'] ?>"><img src="<?php bloginfo('template_url'); ?>/img/facebook.png" alt="facebook" width="55" height="56" /></a>
        <?php } ?>
<?php } // end foreach
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM